Solid Design Principles with Java Series
Welcome to this new series of solid design principles with Java programming language.
In this series we will focus on the most important design principles, introduce them with minimal efforts on both us and the reader, this series should be followed by a more advanced one on design patterns with Java later on – stay tuned!
Single Responsibility Principle (SRP)
On this first lesson, we will discuss the Separation of Concerns (SoC) aka Single Responsibility Principle (SRP).
This is actually a very simple principle, as its name suggests, it means to extract every piece of code logic to its own class.
For example, you have a class called Journal, you clearly should add it’s content to the class itself, but later on, you observed that you need to add a functionality to persist the content of a Journal object to a database, what should you do? simply you go to your Journal class and add 2 new methods to save and load the contents and here we go – but hold on!
What if you have another type of classes, say a Book, that obviously need same logic of persistence? what to do? should you copy and paste your methods from the Journal class? – isn’t this a code smell ?
Let’s think again – why did you add the persistence logic to the Journal class itself? to make things simpler? – wrong, it starts to complicate things.
You should observe now that the persistence logic has nothing to do with the Journal, so go on and build him a new home, maybe a util class.
And that’s it, you just separated the logic of persistence code to its own class. And now, anytime you want to update this code – you will not care about updating it in many places. Congratulations!
Talk is cheap, show me the code 1
or check the code in my GitHub repository !