SOLID – Single Responsibility Principle

Definition:

Every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.
In this principle the class should be only responsible for one thing or one task to do. responsible here means a reason to change, there must be never more than one reason to change your code ‘class’.

 The more responsibilities we have the more likelihood of change and the more changes affects the more errors will be introduced.

 In the SRP we want to strive for low coupling but high cohesion

 cohesion: Is the degree to which the elements of a module or class belong together.

 coupling: Is the degree to which each program module or class relies on each one of the other modules.

So Coupling talks about the inter-dependencies between the various modules while cohesion describes how related functions within a module are.

in this example we have a radio class that is responsible for some operations. We can turn the volume up or down and change the station.

SingleResponsibilityPrincipleRadio

Now the Radio class has two responsibilities, being volume and station management. So if want to modify some of the volume or station management logic changes can affect our code.  By separating these responsibilities into independent classes, we can avoid breakage in other parts of our class when our code needs modification or meets a new requirement.

The class design could end up like this:

SingleResponsibilityPrincipleRadioManagers

Now changes to one responsibility wont have an impact on the rest of the design, and the class design improves maintainability and testability.

Related Posts:
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s