Several days ago, I published a tweet where I asked which of these two statements was better:
dog.expressHappiness();
dog.getBody().getTail().wag();
Many things can be said in favor of the first statement.
A thread
1/6
#SoftwareEngineering #oop #100DaysOfCode


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

#SoftwareEngineering #oop #100DaysOfCode
The first statement:
Increases readability: it expresses the intent of the code clearly.
Reduces complexity: it contains only one method call.
Hides implementation details: it expresses "what" the code does, not "how". 2/6



The second statement makes changes difficult.
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

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

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:
object.doSomething();
This is called the "Tell Don'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
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