The first SOLID principle is Single Responsibility. From its name, it’s very straightforward:
A class should have one, and only one, reason to change.
Each class or type you define should have only one job to do. That doesn’t mean you can only implement one method, but each class needs to have a focused, specialized role.
Remember the example above of adding two numbers, showing the result on screen and writing that operation in a log? Here’s how you’d properly specify those steps in a more organized way:
Perform the addition.
Convert the value to a string.
Get the localized presentation of this string.
Apply attributes like colors and font to the result.
Pass it to different layers of UI.
Open a file on disk that contains all previously calculated math operations.
Count the existing entries and create a new file if the existing operation is more than 100.
Create a new string with the addition operation and its result, the timestamp.
Append this new entry to the file.
Save the file.
If you implement one method to do the 10 steps above, this method will be very long and will do too many things. They’re all related to the functionality you want to deliver, but you shouldn’t blend them.
The first principle tells you not to mix unrelated things. So, for this example, you should create a group of different classes with different responsibilities and have the system put them together to deliver the requirements.
In the next demo, you’ll refactor a system that does the above ten steps in one method to a more organized one that has different modules with focused responsibilities.
See forum comments
This content was released on Oct 17 2023. The official support period is 6-months
from this date.
Download course materials from Github
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress,
bookmark, personalise your learner profile and more!
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.