Hello Guys. Today we learn about first class design principle and its name is Single Responsibility and that is S in SOLID.
As name already describing every thing but I will explain little more and after that I will take one example. In easy words this Principle saying always write a class with giving only one responsibility. Just like in our real life. If some one is a Developer and if you give some design work to him you know what is his reaction. 🙂 In the same manner many times we made functions which having no relationship with the class. I am giving one example which I take from one of my project which I write in the start of 2013. I created a class with name of Utils.class which is bad name but its OK because I need bad code for this example.
. First I am saying to the Util class. Hey you need to manage Logging functionality. As you see in showLog() method.
. Second responsibility I am giving to this class of Toast message. That is related with Android Specific so you can forget this one.
. Third I am giving responsibility of Network Info.
. Fourth I am giving Email and Password validation responsibility.
. Fifth I am giving responsibility of dialog creation.
This type of classes also called God Classes. Which is an Anti Pattern. Now its time to re-factor this class up to that point where these functions will move to there related classes and these new classes will obey the line “Class do one thing”.
Now any functionality which manage Logging will be available in this class. So now I can say that this class has only one responsibility.
Now any where I need to know about is internet connection available? I will use NetworkInfo class. Also class know very well about its responsibility.
All methods which are related to Validation will be available in this class. So validation class know about its responsibility very well.
This class having responsibility to create Dialog when app required.
Now we re-factor our one class into four classes.
1. Code complexity reduced. Again compare Utils class with four other simple classes.
2. Loose couple.
3. More readable and maintainable.
I think that is a good example to realize what is Single Responsibility Principle. If you have any question or suggestion. You can email or comment on this.