Having a lot of small classes make it much easier to maintain a codebase over time. Secondly, this is also an issue of maintainability. It still requires work to make common things happen software has moving parts and each part should be easily identified. Instead, just because we know how to do something doesn’t mean that it’s simple. If it were a simple task, then it wouldn’t necessarily warrant the need for a discussion about it. This is creating a lot of classes to do a simple thing. Yes, this looks a little daunting at first, but the first two objections to this approach are usually easy to put to rest: Displaying the custom post type public view.Displaying the custom post type administrative view.Coordinating hooks with their callback functions.Instead, it looks as if we need to have classes for: Handles serialization and validation for the post type and its meta data.Loads JavaScript files and their dependencies.Registers several actions (and maybe some filters).I think we’re able to convince ourselves that our class does “one thing” by saying “This class is responsible for creating a custom post type.” Literally speaking, the class: Along with the custom post type, additional scripts, styles, meta boxes, and data validation, serialization, and retrieval code must be written. Let’s say that you’re writing a plugin that’s responsible for adding a custom post type. Such a module can be changed for two reasons.Īnd I think there’s difference between saying that a module should “do one thing and do it well” and “have a single reason to change.” Sure, the different is subtle, but let’s contextualize this idea to WordPress. As an example, consider a module that compiles and prints a report. Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change. The Single Responsibility Principle (SRP) states that each software module should have one and only one reason to change.įurthermore, Uncle Bob himself has said the following: The thing is, although the idea behind what are our classes and their functions should do is great, it’s not really what the Principle states. One of the things that we often here is that classes and functions should do “one thing and do it well” and, many times, people attribute this to the Single Responsibility Principle. The Single Responsibility Principle Defined To be fair, I’m as guilty as the next for not always writing very good object-oriented code in the context of WordPress (though I’m slowly working to change that – hopefully the Plugin Boilerplate is proof-positive of that), and I think it’s something that we should all be striving to get better at doing.
0 Comments
Leave a Reply. |