Skip to content

The Power of Composition

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”?

Morpheus definitely uses composition.

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:

https://gist.github.com/anonymous/073d64af30b70da2fdaf74e654cd64ed

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”:

https://gist.github.com/anonymous/c661f8e2766bc16b4976d7e92a7cedc8

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:

https://gist.github.com/anonymous/7565ca625798abe8a189aacb3ac67b9e

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.

Published inSoftware Development