Blog
0

Single Responsibility Principle

  • Pradyumn Sharma
  • July 11, 2017

Tags:

Understanding the principle, and learning how to ensure that we don’t violate it in our design and code.

The Single Responsibility Principle is a fundamental principle of object-oriented design. This term was originally coined by Robert Martin, who says: a class should have only one reason to change. An alternative statement of this principle is: a class should have only one responsibility, and that responsibility should be entirely encapsulated in that class.

A verse in Rigveda, the ancient scripture of India says: एकं सद् विप्रा बहुधा वदन्ति, one truth, wise people say it in many different ways. The two versions of the Single Responsibility Principle, as well as terms like “separation of concerns” and “high cohesion” are different ways of saying the same “truth”.

Let’s take an example. Suppose we have a class that computes the salary for a month for an employee and prints the salary statement. Here the class is handling two different responsibilities: (1) salary computation, based on business rules, and (2) printing the statement. This class seems to be doing too much work.

The class has two potential reasons to change in the future:

1. Changes in business rules for salary computation, and

2. Changes in the way we want the salary statement to be printed (or possibly, we may not want to print the statement at all; we         may, instead, want to save the results in a file or send those as part of a message to some other service).

When a class does too many things:

  • It becomes bloated, making it harder to understand and maintain; this is bad for code organization and readability
  • It may need to be changed more often (as explained above), making it fragile
  • It becomes difficult to reuse as it has extra baggage; another application, for example, may only be interested in one of its responsibilities
  • It requires more testing due to diverse responsibilities it handles
  • Automating testing of the class may become hard, specially if business logic is mixed with things like user interface or database operations.
  • It is low in cohesion; various parts of the class don’t necessarily belong together.

A better alternative would be to separate the two responsibilities (aka ‘concerns’) into two different classes:

  • One to handle the responsibility of salary computation
  • Another to format and print the output

In the future, if the business rules for salary computation change, only one class, the first one, needs to be modified. If the printing requirement changes, only the second class needs to be modified.

If instead of printing, or in addition to it, we decide to save the computed results to a file or send the results as part of a message to another application, we can easily replace the existing class that does the printing, or introduce new classes for the alternative behaviour, without any impact on the class that handles the business rules.

Such separation of concerns into different classes results in smaller classes. Such classes:

  • Are easier to understand and maintain, due to the smaller size
  • Have only one reason to change (business rules / printing requirement)
  • Are easy to reuse, without extra baggage
  • Are easy to test because of only one responsibility
  • Lend themselves to test automation more easily, specially the classes that don’t involve any user interface
  • Are high in cohesion; everything in the class belongs together.

Now, how do we ensure that a class follows the Single Responsibility Principle? Here are a few concepts that you can consider when segregating responsibilities into different classes:

  • Core entities of your application such as Employee, Department, Customer, Supplier, PurchaseOrder, SavingsAccount, etc. Most such classes emerge from the vocabulary of the problem domain, and are, therefore, sometimes referred to as domain classes, or entity classes. These classes would encapsulate the data about the corresponding real-world entities, and the corresponding business rules. Remember that these are not direct representations of your database tables, instead are carefully constructed objects that represent the business needs.
  • Business rules / validations: If the validations are complex or may change independently from the data elements of a class, then it is better to implement these in separate classes. Examples: SalaryCalculator, TaxCalculator, InterestCalculator.
  • User interfaces: Data entry forms, tables that display multiple rows of data, report outputs, query output screens, and the like should all be separate classes. This way changes to the business rules of an application and its UI can be made without impacting each other.

    Related terms such as Model-View Separation Principle, Model-View-Controller (and its variants) emphasize the importance of separating the model (the core of a system, the business data) from the view (user interface).
  • System interfaces: If your application needs to interact with other systems (by way of messaging, or file transfer, or the likes), don’t expose the details of such interactions to all parts of your system. Instead, encapsulate such interfaces in their own classes, with an appropriate interface, and let the rest of the application only rely on such classes to exchange information with the other applications.
  • Device interfaces. If your application communicates with devices, such as temperature sensors or motion detection sensors, encapsulate their APIs in their own corresponding classes. This way, if in the future, you decide to replace one brand of a device with another one, having a different API, you don’t have to make changes all over your application; these will be localized in the device interface classes.
  • Persistence. If you use an O-R mapping framework (like Hibernate) to save your application’s data in some database, you don’t need to do much in your code for this. But if you need to handle persistence on your own, don’t mix the database operations with the business logic of your application. Create separate classes for storing, retrieving, modifying or deleting data.
  • Class selection. If your application needs flexibility in terms of choosing which class from some inheritance hierarchy to select and instantiate, isolate such code in separate classes. Design patterns such as Abstract Factory or Prototype are useful for such purposes.
  • Alternative algorithms or processing rules. If you have alternative algorithms for some task (sorting algorithms, search algorithms), or alternative processing rules (tax calculation for salaried / retired people), create separate classes for each alternative, and provide mechanisms for conditionally, or dynamically, selecting an appropriate class. Design patterns like Strategy, Template Method, Bridge are useful for these purposes.
  • Error Handling. Have separate classes for handling the errors / exceptions in your application. This keeps the rest of the code uncluttered, and makes error handling logic easy to understand and maintain.
  • Logging. Again, this is unrelated to the core behaviour of the application; don’t mix such code with the rest of the application; extract it in separate classes.
  • Similarly, other different, unrelated aspects such as notifications, formatting, parsing of data, etc should also be implemented in separate classes.
  • Begin with a clear separation of concerns as suggested above. Keep in mind, however, that you are never “done” with applying the Single Responsibility Principle. As your system grows, you may find that a class that originally appeared to have a single, well-defined purpose, now seems to be doing too many things. Time to refactor your code.


20 responses to “Single Responsibility Principle”

  1. 加強優化面部輪廓,可被身體完全吸引,能自然地修飾面部輪廓 功效可長達24個月以上 JUVEDERM的特點: 效果立即可見 非永久性 非手術性 安全有效 效果自然 JUVEDERM獲歐盟(CE)及美國及藥物管理局(FDA)認證 首先及唯一獲得FDA認證在首次療程後能維持長達一年2-4功效 新世代專員Hylacross科技為產品帶來獨特的物理特質,包括凝聚力、支撐力及柔順度 8點提升 這是一套由全球著名醫學美容醫生Dr. Maurício de Maio,以JUVÉDERM®系列透明質酸產品為基礎而研發的面部優化療程,藉著簡單程序便達致面部優化效果,不需進行手術,減低風險。 此療程會根據病人的個別情況,重點針對面部8個最常因流失膠原蛋白及彈性纖維而凹陷的位置,再依據特定的順序,從顴骨至下巴位置配合JUVÉDERM®系列的透明質酸產品進行療程,從而改善這些位置的豐盈度及滑溜度,全面性優化面部輪廓。

  2. 櫻花雷射 says:

    JUVEDERM由透明質酸Hyaluronic Acid(一種天然多醣體)製造而成,並具有幼滑及高凝聚力的配方。透明質酸(HA)是皮膚組織的主要成份之一,能自然存在於人體肌膚內 JUVEDERM所用的透明質酸非由動物身體提取,可鎖住水份保濕皮膚,從而增加皮膚密度並改善質感 Juvederm 玻尿酸 加強優化面部輪廓,可被身體完全吸引,能自然地修飾面部輪廓 功效可長達24個月以上 JUVEDERM的特點: 效果立即可見 非永久性 非手術性 安全有效 效果自然 JUVEDERM獲歐盟(CE)及美國及藥物管理局(FDA)認證 首先及唯一獲得FDA認證在首次療程後能維持長達一年2-4功效 新世代專員Hylacross科技為產品帶來獨特的物理特質,包括凝聚力、支撐力及柔順度 這是一套由全球著名醫學美容醫生Dr. Maurício de Maio,以JUVÉDERM®系列透明質酸產品為基礎而研發的面部優化療程,藉著簡單程序便達致面部優化效果,不需進行手術,減低風險。

  3. Are you the type who likes to hangout on social media? Have you ever thought about making it a career? You can help promote their business using social media. This means you can do what you already love doing and make money at it. Does this sound like something you’d like to do? If so, then check out http://d526fc0l5b3nfyfg3bx3sfpbkq.hop.clickbank.net/ You can help people and make some money in the process. You already hang out at social media sites. Why not make a few bucks doing it?

  4. Capuchin says:

    Your post on Single Responsibility Principle – Pragati Software is very good. We hope you can continue delivering many lot post soon. Viva 24x7weboffers.in

  5. Just imagine for a second if you could get into the mind of a millionaire. Think of all the things that you could learn. Well, you actually can do just that. A millionaire is giving away all of his secret right on the internet. You don’t even need to leave the house to learn what made him rich. All it takes is visiting http://e31a67zd-ccr7u13el2cflqp0d.hop.clickbank.net He will literally teach you all of the secrets to making money. Don’t you think it’s time that you earned the living that you deserve? Change your life today by simply following the link above. Do it for yourself and everyone that you care about.

  6. Did you know that people make their entire income promoting ClickBank? You too could be one of the many who have quit their job. Affiliate marketing is as old as the internet. It’s not going to go away any time soon. You too can get your piece of the pie. Why shouldn’t you? Do you really like working the job you have? Are you going to be able to do it until you retire? If you’re job requires physical labor, then you know the answer to that question. There’s no way you’re going to be able to do that when you get older. That’s just the truth and no one needs to tell it to you. Right now you could be making money online. Does it require work? You better believe it does. No honest person is ever going to tell you that it’s possible to become a millionaire online without doing any work whatsoever. It’s not possible. That doesn’t mean there isn’t money to be made. There’s plenty of money out there to be made by people just like yourself. Now you know there’s going to be a pitch for a product. You’re right about that. Click on the link http://64efd6-lz41s3rcelbr7s2xl7x.hop.clickbank.net/ and check it out. There’s a video you can watch that will explain everything. It will tell you how to make money using ClickBank. Watch the video and see what you think. You too can be one of the many who earn a living promoting ClickBank. Some people earn a good living and there’s no reason why you can’t.

  7. It’s rather a terrific along with practical part of info. We are fulfilled which you discussed this beneficial details around. Please keep us all informed such as this.. koleksi youtube indonesia We appreciate you giving.

  8. The weekend is fast approaching. Why not spend it with a sexy cam girl? There’s plenty of them over at http://www.camgirl.pw All of these girls are wanting to have a good time. That’s exactly what you’re looking for too. The most fun you’ll ever have online is right here. Have yourself a good time and meet someone new. That’s what this site is all about.

  9. Are you searching for a date? If so, there’s just one place where you should go. https://t.irtyc.com/vb8tffw9ts?aff_id=29696&offer_id=3785&nopop=1 has more horny singles than any other place online. You can go there and hook up immediately. These are the type of singles who like to have some fun in the sack. Get laid today and put a big smile on your face tonight.

  10. Are you looking for love in all the wrong places? There’s just one site where you can meet all kinds of local singles. There’s never a shortage of girls at this site. By far the best part is, you can go on a date tonight. Hook up here https://t.irtyc.com/awx9mr337k?aff_id=29696&offer_id=3788&nopop=1 and start the day off right. Before you know it, you’ll be in love and hearing the birds sing once again.

  11. lizrose90 says:

    Take a good look at http://www.camgirl.pw This is the one site where you can have a lot of fun. The fun you can have here is exactly what you’re looking for. Enjoy yourself and meet some sexy ladies in the process.

  12. amberlaray says:

    A good time is what you’ll have with the girls at http://www.camgirl.pw. This is by far the most exciting site on the entire internet. Don’t think twice about visiting this site. Not if you’re in the mood to have a little kinky fun.

  13. ryannabanks says:

    Are you searching for a little fun? If you are, then http://www.camgirl.pw is the best site for just that. You’ll find plenty of hot babes there who love to get down and dirty. That’s exactly what you’re looking for right this very second.

  14. It’s been a busy week for you. What’s the best way to get rid of the stress of a busy week? The best and only way is by spending some time with the beauties over at http://www.camgirl.pw These are the girls who know how to treat a man right.

  15. I added a new list. As you’ll see it’s bigger than most of them. I hope you all have had a great week!

  16. Good evening. Thanks for this info! Useful article!.

  17. Good evening. Thank you…Great article.

  18. Hello. Many thanks 🙂 Useful article!.

  19. Good afternoon. Thanks for this info! Interesting page :).

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2017 Pragati Software Pvt. Ltd. All Rights Reserved.

Enquiry