문제

I have this code in some part of an application:

long sum1 = new Multiples().ofAny(new long[] { 3, 5 }).until(32768).sum();
long sum2 = new Multiples().ofAll(new long[] { 3, 5 }).until(32768).sum();
long sum3 = new Multiples().of(32).until(4096).sum();

I created it so readers have a clear vision of what's happening, but each method call returns a different object of a different type (Multiples -> MultiplesCalculator -> MultiplesCalculationResult -> long).

In other words, I am doing A -> B -> C -> D, while Law of Demeter (LoD) recommends only A -> B

Is this a valid use case to break LoD?

도움이 되었습니까?

해결책

The Law of Demeter (AKA The Principle of Least Knowledge) says that it's better to only talk with your friends. It prohibits talking to friends of friends. The reason why is because if you randomly delve into a code base and link together any old random things then you turn what was flexible code into a tangled mess that can't be easily teased apart.

Talking only to your friends limits what you know about and so limits what you care about when change comes. It's nice when a code base can accept a change without forcing you to go fix code in a dozen different packages.

This is what people mean when they say LoD is not a dot counting exercise. It's not a LoD violation just because of the number of dots. What matters is what you're talking to. So long as the dots only take you to your friends you can dot as much as you like.

LoD is fine with what you're doing provided Multiples, MultiplesCalculator, and MultiplesCalculationResult are all friends. That is, they are likely to change together and be deployed together.

What you've created is called an iDSL/eDSL. It's basically a mini language all it's own. They are very powerful but can be a pain to set up. Create them when they will be used often to offset the creation cost.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top