{"id":1405,"date":"2021-03-05T20:13:57","date_gmt":"2021-03-05T19:13:57","guid":{"rendered":"http:\/\/mateuszglowinski.pl\/?p=1405"},"modified":"2021-03-06T14:15:41","modified_gmt":"2021-03-06T13:15:41","slug":"single-responsibility-principle","status":"publish","type":"post","link":"https:\/\/mateuszglowinski.pl\/index.php\/2021\/03\/05\/single-responsibility-principle\/","title":{"rendered":"Single Responsibility Principle"},"content":{"rendered":"\t\t<div data-elementor-type=\"wp-post\" data-elementor-id=\"1405\" class=\"elementor elementor-1405\" data-elementor-settings=\"[]\">\n\t\t\t\t\t\t<div class=\"elementor-inner\">\n\t\t\t\t\t\t\t<div class=\"elementor-section-wrap\">\n\t\t\t\t\t\t\t<section class=\"elementor-section elementor-top-section elementor-element elementor-element-7ca0c07 elementor-section-boxed elementor-section-height-default elementor-section-height-default\" data-id=\"7ca0c07\" data-element_type=\"section\">\n\t\t\t\t\t\t<div class=\"elementor-container elementor-column-gap-default\">\n\t\t\t\t\t\t\t<div class=\"elementor-row\">\n\t\t\t\t\t<div class=\"elementor-column elementor-col-100 elementor-top-column elementor-element elementor-element-c54ef86\" data-id=\"c54ef86\" data-element_type=\"column\">\n\t\t\t<div class=\"elementor-column-wrap elementor-element-populated\">\n\t\t\t\t\t\t\t<div class=\"elementor-widget-wrap\">\n\t\t\t\t\t\t<div class=\"elementor-element elementor-element-93795b2 elementor-widget elementor-widget-text-editor\" data-id=\"93795b2\" data-element_type=\"widget\" data-widget_type=\"text-editor.default\">\n\t\t\t\t<div class=\"elementor-widget-container\">\n\t\t\t\t\t<div class=\"elementor-text-editor elementor-clearfix\"><h4>What is &#8222;Single Responsibility Principle&#8221; (SRP)?<\/h4>\n<p>It is the first rule of the SOLID design rules (it stands for S in SOLID <span lang=\"en\"><span data-language-for-alternatives=\"en\" data-language-to-translate-into=\"pl\" data-phrase-index=\"0\">acronym).<\/span><\/span><\/p>\n<h4>Definition<\/h4>\n<blockquote>\n<div data-md=\"61\" lang=\"pl-PL\">\n<div role=\"heading\" data-attrid=\"wa:\/description\" aria-level=\"3\" data-hveid=\"CAoQAA\">Every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. Or in simple terms: A class or module should have one, and only one, reason to be changed.<\/div>\n<\/div>\n<div role=\"heading\" data-attrid=\"wa:\/description\" aria-level=\"3\" data-hveid=\"CAoQAA\">&nbsp;<\/div>\n<div data-md=\"61\" lang=\"pl-PL\">\n<div style=\"padding-left: 560px;\" role=\"heading\" data-attrid=\"wa:\/description\" aria-level=\"3\" data-hveid=\"CAoQAA\">Robert C. Martin (Uncle Bob)<\/div>\n<\/div>\n<\/blockquote>\n<div>From this quote you should remember sentence &#8222;<strong>A class or module should have once, and only one, reason to changed<\/strong>.&#8221; To understand it better think about Employee class like below:<\/div>\n<div>&nbsp;<\/div>\n<div><img loading=\"lazy\" class=\"aligncenter\" src=\"http:\/\/mateuszglowinski.pl\/wp-content\/uploads\/2021\/03\/Employee-class-not-following-SRP.png\" alt=\"\" width=\"171\" height=\"138\"><\/div>\n<div>Let&#8217;s say that:<\/div>\n<ul>\n<li><em>calculatePay()<\/em> method was prepared by accountent department,<\/li>\n<li><em>reportHours()<\/em> method was prepared by human resources department,<\/li>\n<li><em>save()<\/em> method was prepared by databases administrators.<\/li>\n<\/ul>\n<p>Involving all this methods in one class <span lang=\"en\"><span data-language-for-alternatives=\"en\" data-language-to-translate-into=\"pl\" data-phrase-index=\"0\">violates<\/span><\/span> <i>SRP <\/i>rule, <span lang=\"en\"><span data-language-for-alternatives=\"en\" data-language-to-translate-into=\"pl\" data-phrase-index=\"0\">because the responsibilities of three different departments are interconnected.<\/span> <span data-language-for-alternatives=\"en\" data-language-to-translate-into=\"pl\" data-phrase-index=\"1\">Due to this solution, one change may cause further refactoring in other parts of code.<\/span><\/span><\/p>\n<p>Solution for this problem would be architecture like below:<\/p>\n<p><img loading=\"lazy\" class=\"aligncenter\" src=\"http:\/\/mateuszglowinski.pl\/wp-content\/uploads\/2021\/03\/Employee-SRP.png\" alt=\"\" width=\"551\" height=\"246\"><\/p>\n<p>First what we need to do is to isolate data from methods. That is why we have created <em>EmployeeData<\/em> class, which is data struture without any methods. <em>Employee facade <\/em>is responsible for delegating tasks to other methods (for more details see <a href=\"https:\/\/refactoring.guru\/design-patterns\/facade\" target=\"_blank\" rel=\"noopener\">facade programming pattern<\/a>). <em>PayCalculator<\/em>, <em>HourReporter<\/em> and <em>EmployeeSaver<\/em> classes contain minimal code required for doing their purpose. What is important, those classes are isolated from each other.<\/p>\n<h4>Real-life example<\/h4>\n<p>Let&#8217;s say we have an application that calculates the employee&#8217;s years to retirement.<\/p>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class Launcher {\n\n    public static void main(String[] args){\n        Assistant assistant = new Assistant(30);\n        assistant.handleEmployee();\n    }\n\n}\n<\/pre>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class Assistant {\n\n    public int retrimentAge = 65;\n    public int age;\n\n    public Assistant(int age) {\n        this.age = age;\n    }\n    public void handleEmployee(){\n        System.out.println(\"Logging data...\");\n        System.out.println(this.retrimentAge - this.age);\n    }\n\n}\n<\/pre>\n<p><em>Assistant<\/em> class is kind of God class, which handles logging&nbsp; and calculations, due to that application at this moment does not meet <i>SRP <\/i>rule.<\/p>\n<p>UML for <em>Assistant<\/em> class is like below:<\/p>\n<p><img loading=\"lazy\" class=\"aligncenter\" src=\"http:\/\/mateuszglowinski.pl\/wp-content\/uploads\/2021\/03\/Assistant-no-SRP.png\" alt=\"\" width=\"192\" height=\"138\"><\/p>\n<p>Let&#8217;s refactor the code according to <em>SRP<\/em> rule. We should start with separating logging and calculations to two different classes. It might also be good idea to use&nbsp;<a href=\"https:\/\/en.wikipedia.org\/wiki\/Object_composition\" target=\"_blank\" rel=\"noopener\">composition<\/a> and create class for delegating the tasks.<\/p>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class Launcher {\n\n    public static void main(String[] args){\n        Assistant assistant = new Assistant(30);\n        assistant.handleEmployee();\n    }\n\n}\n<\/pre>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class Assistant {\n \n    private FinanceAssistant financeAssistant;\n    private Logger logger;\n \n    public Assistant(int age) {\n        this.financeAssistant= new FinanceAssistant(age);\n        this.logger = new Logger();\n    }\n \n    public void handleEmployee(){\n        this.logger.log();\n        this.financeAssistant.calculate();\n    }<br>\n}\n<\/pre>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class Logger {\n     \n    public void log() {\n        System.out.println(\"Logging data...\");\n    }<br>\n}\n<\/pre>\n<pre style=\"background-color: lightgrey; color: black; border-radius: 5px;\">public class FinanceAssistant {\n \n    public int retirementAge = 65;\n    public int age;\n \n    public FinanceAssistant(int age) {\n        this.age = age;\n    }\n \n    public void calculate() {\n        System.out.println(this.retirementAge - this.age);\n    }<br>\n}\n<\/pre>\n<p>After code refactoring, the UML looks like:<\/p>\n<p><img loading=\"lazy\" class=\"aligncenter\" src=\"http:\/\/mateuszglowinski.pl\/wp-content\/uploads\/2021\/03\/Assistant-SRP.png\" alt=\"\" width=\"571\" height=\"371\"><\/p>\n<h4>Why should I follow &#8222;Single Responsibility Principle&#8221; ?<\/h4>\n<p>This rule helps to maintain the code, due to that changes are isolated. Code is less complex and therefore easier to understand and reuse.<\/p>\n<h4>What to look for?<\/h4>\n<p><i>SRP <\/i>rule is not defined by sentence that a class should be doing only once job. It is common mistake in this rule, probably caused by a<span lang=\"en\"><span data-language-for-alternatives=\"en\" data-language-to-translate-into=\"pl\" data-phrase-index=\"0\"> bit of a misnomer.<\/span><\/span><\/p><\/div>\n\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t<\/section>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>\n\t\t","protected":false},"excerpt":{"rendered":"<p>What is &#8222;Single Responsibility Principle&#8221; (SRP)? It is the first rule of the SOLID design rules (it stands for S in SOLID acronym). Definition Every&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[34],"tags":[35],"_links":{"self":[{"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/posts\/1405"}],"collection":[{"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/comments?post=1405"}],"version-history":[{"count":118,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/posts\/1405\/revisions"}],"predecessor-version":[{"id":1718,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/posts\/1405\/revisions\/1718"}],"wp:attachment":[{"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/media?parent=1405"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/categories?post=1405"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mateuszglowinski.pl\/index.php\/wp-json\/wp\/v2\/tags?post=1405"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}