Das Gesetz von Demeter ist sehr verwirrend, weil ich aussieht, als hätte ich keine Methoden schreiben, die Objekte zurücksenden

StackOverflow https://stackoverflow.com/questions/5050083

Frage

Es fühlt sich an, als wäre ich zu einem Sackgasse gekommen.Wenn ich es richtig verstanden habe, dann, wenn ich dem das Gesetz von Demeter kann, kann ich niemals eine Methode erstellen, die zurückkehrtEin Objekt und dann nimmt Client-Code dazu auf.Ich denke nur an das Fabrikmuster, das immer ein Objekt zurückgibt.Ja, es gibt Mapper-Klassen, die Objekte zurücksenden.Und wie wäre es mit Sammlungen?

War es hilfreich?

Lösung

You've misunderstood the Law of Demeter and are applying it beyond the point of usefulness:

More formally, the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects:

  • O itself
  • M's parameters
  • any objects created/instantiated within M
  • O's direct component objects
  • a global variable, accessible by O, in the scope of M

Factories in particular are used to create an object, and the type of object they create is part of their public interface. Thus, calling methods of an object created by a factory is allowed by the above.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top