Search code examples
javalaw-of-demeter

Does System.out.println violate the law of demeter?


Does System.out.println violate the law of demeter?

If not, why?


Solution

  • Depending on view.

    LoD: Yes, because it uses the console. Under LoD you can't assume access.

    LoD-F: Yes, because it uses more than one dot. The LoD-F states that in any method usage only the object may know the internal structure of itself. IE

    System.out.println() 
    

    requires knowledge of the structure of system (that it has .out) to reach println(),

    For System to not break LoD-F it would have to be

    System.println()
    

    To break the formal rules down with example, println() (the method) may only access:

    1. system itself
    2. println()'s parameters
    3. any objects created/instantiated within println()
    4. system's direct component objects
    5. a global variable, accessible by system, in the scope of println()

    (I know, it's a reversed reference here as the code should be the method calling it, but it actually swings both ways.)