Does System.out.println violate the law of demeter?
Does System.out开发者_如何学Python.println
violate the law of demeter?
If not, why?
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:
- system itself
- println()'s parameters
- any objects created/instantiated within println()
- system's direct component objects
- 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.)
System.out
is actually a "global state", and yes, technically it violates the "law of demeter". But:
- you should avoid using
System.out.println(..)
. Use a logger (log4j, logback, slf4j) instead. - you are not supposed to rely (and test) anything that's for the purpose of logging to a console. (this does not concern complex logging systems that later aggregate the logged information)
No.
System.out
is a global variable.
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:[2]
- 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 <- This one
-- Wikipedia
By the 5th rule, you can invoke any method of the global variable System.out
from within any context.
I'd say not really, since it calls Object.toString()
and doesn't tightly couple with any class in any way; it just tells the object to convert itself to a string.
Edit:
If you mean the call itself, rather than what happens in the call, then I'd say yes it does, because it tightly couples your program to the System.out
field.
It breaks the law, since it uses "more than one dot", and exposes the fact that it is using another object for the println call.
精彩评论