Exercise 26 pragmatic programmer

There is a code snippet presented in “Pragmatic Programmer” on page 143 as:

public class Colada { private Blender myBlender; private Vector myStuff; public Colada() { myBlender = new Blender(); myStuff = new Vector(); } private doSomething() { myBlender.addIngredients(myStuff.elements()); } } 

This is subject to the Law of Demeter / Principle of Least Knowledge.

This is preferable, and are there any reservations, replacing it with the following, which uses dependency injection?

 public class Colada throws IllegalArgumentException { private Blender myBlender; private Vector myStuff; public Colada(Blender blender, Vector stuff) { if (null == blender) { throw new IllegalArgumentException() } else { myBlender = blender; } if (null == stuff) { throw new IllegalArgumentException() } else { myStuff = stuff; } } public static Colada createDefaultInstance() { Blender blender = new Blender(); Vector stuff = new Vector(); return new Colada(blender, stuff); } private doSomething() { myBlender.addIngredients(myStuff.elements()); } } 
+4
source share
2 answers

How you structure the creation of objects is a separate issue than the drop-down API .

Demeter’s Law says something about the API classes, not how they are built, so I don’t see a conflict between the Injection construct and the Demeter Law.

However, once you decide to use Dependency Injection, you should be careful to avoid ambiguity when it comes to creating objects. If you continue to offer a parameterless constructor or a static factory method, people can use this instead of letting the external caller build a hierarchy of dependencies.

Each time developers accidentally destroy the hierarchy of dependencies using the factory method (or a parameterless constructor), they introduce a hard link at this point. When you decide to use DI, you can best benefit from this in order to do this consistently.

+4
source

public getInstance (), shouldn't be "public static Colada getInstance ()"?

Both are good in my world, the first is more readable, the second is more dynamic. But none of them says that myBlender and myStuff are properties, so it's hard to understand why you prefer it to dynamic. But if this is what you want, everything looks good. Instead of getInstance, I would simply create two constructors, but without arguments, such as the first example, and one with two, as the second

Greetings

Nick

+2
source

Source: https://habr.com/ru/post/1304542/


All Articles