Learn the Single Responsibility Principle.

That thing should have one job.

The first amongst the SOLID principles is the single responsibility principle. Programming with the five SOLID principles will lead to software that is easier to understand and maintain, and thus is a worthy goal.

The single responsibility principle says that a class should have only one job. If changes occur to the software’s specifications, only one part of the changes should be able to affect the specifications of the class. If this is not the case, then the class probably has multiple responsibilities, a situation that one should avoid. The class should only have one reason to change.

Examples of responsibilities include persistence, validation, notification, error handling, logging, class selection, formatting, parsing, and mapping. While it may seem extreme to have a separate class for each of these, it does lead to better code.

Software written this way is less likely to break things that are not related to the requested change. Often, in immature software applications, a single change in requirements can have adverse effects all over the codebase.

It would be best if you encapsulated the responsibility handled by the class within the class. The responsibility is this class’s job, and it should not appear in any other class.

Following this technique leads to more robust code that is resistant to unwanted side effects due to a change.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: