Every time I work on a project for a client (or a side project for myself), I try to keep in mind each of the five SOLID principles.

These are often talked about by developers on numerous blogs (and I’ve done so myself on this site), so I’m not about to teach of them in this post.

Single Responsibility: One Reason to Change

Instead, I’ve been looking at how the Single Responsible Principle applies with working with various aspects of the WordPress API. And what I’ve found is that, in my experience, using this principle consistently results is far smaller classes.

My most recent experience has been in a very simple use case: Working with the WordPress API to create a submenu item and a corresponding submenu page.

Single Responsibility Principle

Often, the Single Responsibility Principle is described as follows:

A class, and each of its methods, should have a one job.

But that’s not actually what the principle says. In fact, you may end up saying something like “The single responsibility principle states that a class should have a single responsibility.” And that’s begging the question, isn’t it?

Instead, this has to do more with separation of concerns, and that’s a topic for another post.

Instead, the principle says the following:

A class should have only one reason to change.

Though that’s easier to express, it’s not necessarily easier to apply. In fact, I think it makes it a bit more challenging because rather than asking:

  • “What’s the job of this function (or class)?”

We have to ask:

  • “If this class was to change, what would need to be changed?”

And if we’re able to provide more than one answer, then we know we’re violating the principle.

What About Menus?

At the beginning of the post, I said that I was working with this in the context of using submenus and their corresponding pages. Over the next couple of posts, I’m going to walk through an example of how this looks.

But I thought it was important to cover the single responsibility principle, contrast it with a popular misconception, how to think about it when working with classes.

Without that foundation, the following posts won’t make any sense. Above all else, the main takeaway is to ask yourself, when designing a class, what ways a class may change over time.

And if you have more than one answer, consider redesigning your class.


Join the conversation! 1 Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.