Instruction 2

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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:

  1. Perform the addition.
  2. Convert the value to a string.
  3. Get the localized presentation of this string.
  4. Apply attributes like colors and font to the result.
  5. Pass it to different layers of UI.
  6. Open a file on disk that contains all previously calculated math operations.
  7. Count the existing entries and create a new file if the existing operation is more than 100.
  8. Create a new string with the addition operation and its result, the timestamp.
  9. Append this new entry to the file.
  10. 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
Download course materials from Github
Previous: Instruction 1 Next: Demo 1