Injecting only the minimum required into a constructor or function - is there common terminology for this principle?

softwareengineering.stackexchange https://softwareengineering.stackexchange.com/questions/399254

  •  02-03-2021
  •  | 
  •  

Question

Probably best explained with an example:

In a .NET C# project, we have a library class for which several function accept an HttpContext as one of the arguments.

The thing is, that none of the functions actually need the full HttpContext, they just need one item from one of the collection properties on the HttpContext.

I need to convey the idea that having a method parameter that is more than what the function actually needs to run is sub optimal because it:

a) Requires the caller to have more than what they might in order to call the function.

b) Makes testing harder.

c) Is potentially less performant.

But my googling has not helped me find canonical terminology for this.

Does it exist?

Was it helpful?

Solution

This is known as the Principle of Least Knowledge or The Law of Demeter.

OTHER TIPS

The Interface Segregation Principle states that:

No client should be forced to depend on methods it does not use

Wikipedia - Interface Segregation Principle

So shoving bloated objects into clients without a narrowing interface that shows the clients actual needs violates the principle.

A method parameter that only contains what is needed would satisfy the principle, so would a narrow interface between HttpContext and the client. Either way will show what the clients actual needs are. No more. No less.

I would not label this ISP. ISP is not about limiting client access, it is about isolating behavioral aspects. What you are referring to is maintaining tight scope. You do not want (the method's) code to see more than what is relevant to its purpose, thus eliminating noise for the reader and inhibiting the code to do things it is not supposed to do.

Licensed under: CC-BY-SA with attribution
scroll top