Can multiple operations with Streaming break The Law of Demeter? Can multiple operations with Streaming break The Law of Demeter? selenium selenium

Can multiple operations with Streaming break The Law of Demeter?


Java 8 streams are an example of a fluent interface, and are intended to allow writing in a functional programming style. There is a lot of disagreement over what breaks the LoD and whether it even matters, but all that aside, the example in the documentation for Stream shows that you are using it as intended by the Java language designers.

If that isn't enough for your reviewer, note that the purpose of the Law of Demeter (aka the principle of least knowledge) is to keep programs loosely-coupled by minimizing the number of classes that a class directly communicates with. When A has a B and B has a C, and you want A to make C do something, you should have it tell B to get it done and let B worry about the details of how and when C is used.

In this case, every intermediate method on Stream is returning another instance of Stream, so you are still only coupled to the Stream class. I would not consider this a Law of Demeter violation.

I would also say that any class in a language should be considered coupled to the language's standard library. Therefore, any standard library objects should be exempt from the Law of Demeter, since you can't uncouple from them anyway. Otherwise, you wouldn't even be able to call get on a List that was returned by an object, or deal with a Set of Map.Entry from Map.entrySet(). This would also cover Stream, of course.

I was suggested to break the code to first stream to collect to list and run another stream operation to do match( in short break it down into multiple streams as needed).

Storing intermediate objects in local variables does not fix a Law of Demeter violation, you would still be accessing objects returned by other objects. It sounds like your reviewer is just blindly dot-counting.


Here is a detailed explanation of the Law of Demeter. There is some gray area of course, but it is actually quite well defined.

As the answer from Sean Van Gorder pointed out, working with Streams in itself does not constitute a violation of the LoD, neither does chaining method calls.

What is however most likely a violation is this part:

element.getText().contains(name);

According to LoD, you can not access/call a method on anything that you don't have direct access to. I assume, that getText() returns some internal state of the element. That is not something you have direct access to, therefore the contains(name) method call is illegal.