9

It feels like I've come to a dead end. If I understood it right then if I follow the Law of Demeter I can never make a method that returns an object and then client code makes calls to it. I'm just thinking about the Factory Pattern which always returns an object. Yes, there are mapper classes that return objects. And how about collections?

SCFrench
  • 8,244
  • 2
  • 31
  • 61
PPPHP
  • 747
  • 10
  • 20

1 Answers1

14

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.

Thomas Edleson
  • 2,175
  • 1
  • 16
  • 19
  • It seems to me that LOD violations stem mainly from having objects expose references to entities which the recipient will not own (a factory method's caller receives ownership of the generated object). Rather than worrying about whether one may legitimately use nested methods and properties, a bigger question in my mind would be whether references to *entities* should be exposed in the first place. – supercat Nov 11 '13 at 23:57