Avoid the “just a couple more lines” syndrome.
Composition saves your day.
I can never stress this enough.
After many years spent developing systems at different scales, this principle always holds true for me.
Composition is one of the fundamental tools you have, as a Software Developer, to face the daily challenge of continuous change in your codebase (thank you, Product Manager).
I often hear the argument that using composition brings in more code than necessary.
Just a couple more lines will do the job. And the overall result is still readable.
But for how long?
And what about the Single Responsibility Principle on the class you are adding “just a couple more lines” to?
What about its testability?
What about staying flexible for future requirements and control the evolution of your code base?
Will you be comfortable to look into the face of your PM and say “C’mon, give me more requirements”?
Not if you approach change thinking about the now only.
Not if you don’t exercise discipline in your profession.
Not if you don’t use Composition and violate SOLID principles.
I’ll give you an example.
This is your current interface and implementation of an in-memory message publisher:
Now your PM comes and tell the team:
- “We need to plug a Kafka cluster in where we need to throw in all messages that we currently publish in-memory”
- “We still need to keep publishing those messages in the in-memory publisher”
You have a choice here.
The first possibility is to add “just a couple more lines”:
Tell me, are you able to easily test this class? All the cases?
How many things is this class doing? Only one or more?
Now the second possibility:
How easy is to test each of those classes?
How many things are each of those classes doing?
If you would need to add a third Publisher tomorrow, or change your message distribution policy, which strategy would make you faster and safer?
Adding “just a couple lines more” in an ever growing class or adding another tiny, single responsibility driven class?
Think about it.