Does System.out.println
violate the law of demeter?
If not, why?
getObjectC(). display() this sort of statement is a violation of Law of Demeter. There are primarily 4 principles of the least knowledge in java as follows: Method M of an object O can invoke the method of O itself.
out. println is an IO-operation and therefor is time consuming. The Problem with using it in your code is, that your program will wait until the println has finished.
The Law of Demeter asks us to minimize coupling between classes and avoid reaching out to the third object in order in order to make refactoring and developing new features easily.
The law dates back to 1987 when it was first proposed by Ian Holland, who was working on the Demeter Project.
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:
(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:
System.out.println(..)
. Use a logger (log4j, logback, slf4j) instead.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With