This is an old revision of the document!


Single Responsability Principle vs. Polymorphism

First off, some definitions to establish the context of this article.

The SRP states that “one class should have only one reason to change”. This principle was then further refined and there are various discussions about it in SRP.

Polymorphism on the other hand means that an object can be of different types. In typical OO languages, polymorphism is achieved through two mechanism: inheritance and/or implementing different interfaces/contracts (related principle: ISP).

The conflict

The conflict between these two principles arises from the very definition of SRP. If taken as-is, you cannot respect SRP and use polymorphism without any danger.

As soon as your class implements multiple interfaces, by default, the class will have different reasons to change – why would you otherwise seggregate those interfaces?

Fundamentally, I think that the SRP was defined sloppily from the very beginning. Polymorphism is a core trait of many OO languages, so it is more central to the “concept graph of OO”, and other principles like SRP are not supposed to violate the core, they're supposed to enrich it and give new insights and perspectives.

A saner definition of SRP

For this reason, I'm an advocate of the following definition of SRP:

  • a type should have only one reason to change

What is a type?

A type is:

  • the class itself
  • any of the base classes
  • any of the interfaces that the class implement

What is a "reason to change"?

Whether a type violates or not the SRP can be decided only after looking at the recorded history of the code over time. The SRP does not make sense without this analysis. That comes from the corrected definition of “reason to change”:

However, as you think about this principle, remember that the reasons for change
are people. It is people who request changes. And you don’t want to confuse
those people, or yourself, by mixing together the code that many different people
care about for different reasons. 1)