Several days ago, I published a tweet where I asked which of these two statements was better:

https://abs.twimg.com/emoji/v2/... draggable="false" alt="1⃣" title="Tastenkappe Ziffer 1" aria-label="Emoji: Tastenkappe Ziffer 1"> dog.expressHappiness();
https://abs.twimg.com/emoji/v2/... draggable="false" alt="2⃣" title="Tastenkappe Ziffer 2" aria-label="Emoji: Tastenkappe Ziffer 2"> dog.getBody().getTail().wag();

Many things can be said in favor of the first statement.

A thread https://abs.twimg.com/emoji/v2/... draggable="false" alt="🧵" title="Thread" aria-label="Emoji: Thread"> 1/6

#SoftwareEngineering #oop #100DaysOfCode
The first statement:

https://abs.twimg.com/emoji/v2/... draggable="false" alt="🔹" title="Kleine blaue Raute" aria-label="Emoji: Kleine blaue Raute"> Increases readability: it expresses the intent of the code clearly.
https://abs.twimg.com/emoji/v2/... draggable="false" alt="🔹" title="Kleine blaue Raute" aria-label="Emoji: Kleine blaue Raute">Reduces complexity: it contains only one method call.
https://abs.twimg.com/emoji/v2/... draggable="false" alt="🔹" title="Kleine blaue Raute" aria-label="Emoji: Kleine blaue Raute">Hides implementation details: it expresses "what" the code does, not "how". 2/6
The second statement makes changes difficult.

https://abs.twimg.com/emoji/v2/... draggable="false" alt="❓" title="Rotes Fragezeichen-Symbol" aria-label="Emoji: Rotes Fragezeichen-Symbol"> What happens if happiness must now be expressed by "jumping and barking"?

We have to apply changes in all places where statement 2 (or a similar version of it) appears.

This is how systems become *rigid* and hard to change. 3/6
https://abs.twimg.com/emoji/v2/... draggable="false" alt="📔" title="Notizbuch mit verziertem Umschlag" aria-label="Emoji: Notizbuch mit verziertem Umschlag"> The "Law of Demeter" says that a module should not know about the internals of the objects it manipulates.

Statement 2 violates this principle because it asks the dog about its internal structure (body and tail).

Statement 2 breaks encapsulation and increases coupling. 4/6
We should not be forced to traverse the graph of objects, searching for the method we want to call. We should be able to directly tell an object what to do:

https://abs.twimg.com/emoji/v2/... draggable="false" alt="➡️" title="Pfeil nach rechts" aria-label="Emoji: Pfeil nach rechts"> object.doSomething();

https://abs.twimg.com/emoji/v2/... draggable="false" alt="📔" title="Notizbuch mit verziertem Umschlag" aria-label="Emoji: Notizbuch mit verziertem Umschlag"> This is called the "Tell Don& #39;t Ask" principle. 5/6
The first statement facilitates testing.

If we want to unit test a piece of code that calls the "expressHappiness" method, we can mock the implementation of this method.

We do not need the whole dog object implemented. 6/6
You can follow @macerub.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: