HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Law of Demeter and data models?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lawandmodelsdatademeter

Problem

Inspired by this question, but hopefully not a duplicate.

I understand that the Law of Demeter is very useful in case of services interacting with other services, for example it's much easier to mock the other services in unit tests.
What about services interacting with data models, though?

Let's say I have a hierarchy of immutable classes:

public final class Document {
    private final List pages;
    // Constructor, getter, ...
}

public final class Page {
    private final List paragraphs;
    // Constructor, getter, ...
}

public final class Paragraph {
    private final List lines;
    // Constructor, getter, ...
}


Let's say I want to do something with certain lines in a document doc:

public void doSomething(Document doc) {
    for (Page page : doc.getPages()) {
        for (Paragraph para : page.getParagraphs()) {
            for (Line line : para.getLines()) {
                if (someCondition(line)) {
                    someAction(line);
                }
            }
        }
    }


Now, as far as I understand, the above code doesn't obey the Law of Demeter.
However, I don't want to force the law at all cost and clutter the model (here, the Document class) with tens of methods like:

public List filterWrtSomeCondition();
public List filterWrtSomeOtherCondition();


Or maybe there's a third way? I suspect that the Law of Demeter applies primarily to services interacting with other services. Is it a valid interpretation?

Solution

For some perspective on the LoD, read "The Law of Demeter Is Not A Dot Counting Exercise". In particular the part under the heading "I Fought The Law and The Law Won".

I think in this instance that pages, paragraphs and lines are very logical subcomponents of documents. These each have different but related behaviour. The each also serve different purposes.

Forcing the document to handle interactions with subcomponents will - as you say - lead to clutter (and more chance of introducing troublesome issues).

The big thing about the LoD is that it aims to reduce coupling. However adding methods to Document doesn't really reduce coupling as you're still writing code that says "do x to line y" - you're just asking Document to do it for you.

Don't get me wrong, the LoD is useful. But like all principles it has to be used correctly to stay useful.

(Funnily enough a similar question with a similar answer as been asked at SO.)

Conclusion

In short I don't see any benefit for you in talking to Document rather than it's contained Pages, Paras, & Lines. Frankly I don't think there's any ROI for you.

Context

StackExchange Code Review Q#131, answer score: 16

Revisions (0)

No revisions yet.