Marco

Single Responsibility Principle states that a class should have one and only one reason to change. That means, if we have two reasons for a class to change, we should split this class into two different classes instead of one, and each of which will be concerned only with one responsibility.

To explain this more, let’s have a look at the following class diagram:

Description: SRP-1.jpg

From the first look at the above class diagram, you will know that it is a real-world bank account representation, but with two extra responsibilities (other than modeling); which are saving and printing the bank account. Now the BankAccount class will have three reasons to change:

  • Updates in the BankAccount class structure itself (properties, and methods).
  • Updates in the way the BankAccount is saved (to database, to files …etc).
  • Updates in the way the BankAccount is printed (to the screen, to a printer …etc).

Now, in order to maintain the Single Responsibility Principle in the above example; we are going to divide the BankAccount class into three different classes, and each of which will have only one responsibility to take care of, and accordingly one reason to change.

See the class diagram below after applying the Single Responsibility Principle to it.

Description: SRP-2.jpg

Leave a Reply

Your email address will not be published.

Captcha Time limit is exhausted. Please reload the CAPTCHA.