Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

If not, why?

like image 607
Billworth Vandory Avatar asked Jan 01 '11 21:01

Billworth Vandory


People also ask

Which of these code examples violates the principle of least knowledge or Law of Demeter?

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.

Why system out Println should not be used?

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.

What is the Law of Demeter trying to prevent?

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.

Which proposed the Law of Demeter?

The law dates back to 1987 when it was first proposed by Ian Holland, who was working on the Demeter Project.


2 Answers

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.)

like image 178
Mantar Avatar answered Sep 26 '22 06:09

Mantar


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)
like image 42
Bozho Avatar answered Sep 24 '22 06:09

Bozho