Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

A. SOLID Principles of Class Design > Single Responsibility Principle (SRP)

Single Responsibility Principle (SRP)

Classes should change for only a single reason.

The basis for this principle is cohesion. Cohesion represents the measure to which a class performs a single function. Classes that are highly cohesive are easier to understand. But they are also easier to maintain. This is the motivating force behind SRP. If a class has more than one reason to change, then it stands to reason that the responsibilities of that class that are the cause of change should be separated into multiple classes.

Cohesion is not a concept new to objects. In fact, the concept is taught in most introductory programming courses. Ironically, I found that although most developers can easily define cohesion and explain its benefits, few developers actually apply it. Cohesion measures the degree to which an entity does a single thing. Given this definition, it’s no surprise that if some entity is responsible for performing only a single thing, most of our entities should be fairly small. Yet, I commonly come across methods that run well over 100 lines of code and classes that run orders of magnitudes larger than that. I struggle to convince myself that either is cohesive. When you’re designing a highly cohesive system, you have to think small.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint