{"id":420,"date":"2020-08-05T18:22:48","date_gmt":"2020-08-05T12:52:48","guid":{"rendered":"https:\/\/saurabhjain1537.wordpress.com\/?p=420"},"modified":"2025-02-27T07:46:42","modified_gmt":"2025-02-27T07:46:42","slug":"solid-principles-single-responsibility","status":"publish","type":"post","link":"https:\/\/saurabhjain.dev\/?p=420","title":{"rendered":"SOLID Principles: Single Responsibility"},"content":{"rendered":"\n<p class=\"has-medium-font-size\"><strong>Introduction<\/strong><\/p>\n\n\n\n<p>SOLID Design Principles are tips and tricks to organize the code in different classes which helps in keeping the code clean, maintainable and scalable (or extensible).<\/p>\n\n\n\n<p>The way software modules &amp; classes are designed &amp; organized have a major impact on the people associated with it:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Programmers:  The application can be easy to manage and extends.<\/li><li>Business owners: The application can be quickly enhanced to add business critical and compliance mandatory functionalities.<\/li><li>Users: The application can provide improved experience and help achieve more.<\/li><\/ol>\n\n\n\n<p class=\"has-medium-font-size\"><strong>The Single Responsibility Principle &#8220;S&#8221;<\/strong><\/p>\n\n\n\n<p>As the name suggests, a class should be responsible for one and only one thing. In words of Robert C. Martin &#8220;A class should have only one reason to change&#8221;.<\/p>\n\n\n\n<p>Although it seems pretty obvious &amp; it is basic Object Oriented Design, but still it gets defied many times.<\/p>\n\n\n\n<p>Consider this example of <strong>LogManager<\/strong> class having a field Enum <strong>LogType<\/strong> with possible values of FileBased, DBBased:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"203\" height=\"213\" src=\"https:\/\/saurabhjain.dev\/wp-content\/uploads\/2020\/08\/01-srp-01.png?w=203\" alt=\"\" class=\"wp-image-426\" \/><figcaption>Figure 1<\/figcaption><\/figure><\/div>\n\n\n\n<p>The <em>log()<\/em> method converts Object to string and logs the string to File or DB conditionally:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    void log(Object obj) {\n\n      String message = convertToJson(obj);\n\n      switch(logType) {\n        case FileBased:\n          logToFile(message);\n          break;\n\n        case DBBased:\n          logToDB(message);\n          break;\n      }\n\n    }<\/code><\/pre>\n\n\n\n<p>The purpose of above code is to perform logging, it seems to be doing fine by logging into a File or DB and it includes some helpers like converting an Object to JSON string.<\/p>\n\n\n\n<p>However, this class has two reasons to change:<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Changes in the way messages are logged<\/li><li>Changes in the way String is created<\/li><\/ol>\n\n\n\n<p>In future, it may be decided to log messages as xml or csv or any other format. OR a different library may be used for converting Object to json string. But it should not impact the way strings are being persisted to storage (either File or DB).<\/p>\n\n\n\n<p>Doing multiple things in a single class makes it tightly-coupled:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Some variable may be reused<\/li><li>Low level and Mid level methods may get mixed. e.g. <em>log(String msg)<\/em>  should have been a low level method (only writing the string to storage) but <strong>LogManager <\/strong>class has <em>log(Object obj)<\/em> which is mid level method invoking <em>convertToJson(Object)<\/em>.<\/li><\/ul>\n\n\n\n<p>In a class like this, it becomes very difficult to change something in isolation. A fix in one part of class impacts other parts too and might break something unintentionally.<\/p>\n\n\n\n<p>A better design is to create a <strong>Serializer<\/strong> Interface for converting Object to string. Implement a <strong>JSONSerializer<\/strong> for json string conversion. <\/p>\n\n\n\n<p>Use abstraction (Serializer) in the <strong>LogManager<\/strong> class:<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"387\" height=\"293\" src=\"https:\/\/saurabhjain.dev\/wp-content\/uploads\/2020\/08\/01-srp-02-logger.png?w=387\" alt=\"\" class=\"wp-image-436\" \/><figcaption>Figure 2<\/figcaption><\/figure><\/div>\n\n\n\n<p>The <strong>LogManager <\/strong>class doesn&#8217;t need to know how serialization is happening and the <em>log()<\/em> method should depend on Abstraction for Serialization:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>    void log(Object obj) {\n\n      String message = serializer.serialize(obj);\n\n      switch(logType) {\n        case FileBased:\n          logToFile(message);\n          break;\n\n        case DBBased:\n          logToDB(message);\n          break;\n      }\n\n    } <\/code><\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Conclusion<\/strong><\/p>\n\n\n\n<p>Single Responsibility principle helps in :<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>Making the classes loosely-coupled <\/li><li>Minimizing the impact of a change (bug-fix or enhancement)<\/li><li>Making the code easy to understand<\/li><\/ol>\n","protected":false},"excerpt":{"rendered":"<p>Introduction SOLID Design Principles are tips and tricks to organize the code in different classes which helps in keeping the code clean, maintainable and scalable (or extensible). The way software modules &amp; classes are designed &amp; organized have a major impact on the people associated with it: Programmers: The application can be easy to manage &hellip; <a href=\"https:\/\/saurabhjain.dev\/?p=420\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">SOLID Principles: Single Responsibility<\/span><\/a><\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[2],"tags":[53,55,58],"class_list":["post-420","post","type-post","status-publish","format-standard","hentry","category-design","tag-single-responsibility","tag-solid-principles","tag-srp"],"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/posts\/420","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=420"}],"version-history":[{"count":1,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/posts\/420\/revisions"}],"predecessor-version":[{"id":782,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=\/wp\/v2\/posts\/420\/revisions\/782"}],"wp:attachment":[{"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=420"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=420"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/saurabhjain.dev\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=420"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}