Quantcast
Channel: mentis vulgaris
Viewing all articles
Browse latest Browse all 10

SOLID 101: New it, or Use it. Pick one.

$
0
0

New It or Use It.

This describes an extremely simple technique in writing software that will stay soft and play nice with changes. Said another way, an object can either allocate another object, or call methods on the object — it can’t do both.

To understand why that’s important, let’s go back to some of those SOLID principles.   In particular, the Dependency Inversion Principle (DIP).   Recall, this says code should only depend on (e.g., “call”, “use” or interact with) abstractions instead of details.   For example, Shape.Draw may be an abstraction of Circle.Draw, Line.Draw, Square.Draw, etc.   Code that only calls Draw through the Shape abstraction will never need to change when we add new kinds of Shapes.

When we “new” an object, on the other hand, we aren’t dealing with abstractions.   We’re dealing with the actual type:

Shape shape = new Square();

The method (and object) calling this code knows the details about what type it is interacting with (a Square).   Adding insult to injury, not only does it know the specific type, it also knows the object was allocated on the heap, right now (it can’t be a Proxy object wrapping a remote interface, supplied at program startup, for example).   Not one, but two details client code doesn’t really need to care about.

To hide these details, and get us back to abstractions, we need to recognize allocation and construction are implementation details.

So, to fix this, do we  just wrap that information up in another method (aka, a Factory Method), and call that new method?

Maybe.   It depends on two things:  where you define that factory method, and when you call it.  I’ll cover that in a future post.


Viewing all articles
Browse latest Browse all 10

Latest Images

Trending Articles



Latest Images