Most web coders use frameworks these days. That's a good start. But the single responsibility principle (SRP) still matters as your app grows.
The single responsibility principle states that:
Each class or module should only look after one aspect of functionality
Robert C Martin is a software engineer who co-authored the Agile Manifesto.
He said: "A class should have only one reason to change."
It's OK, I'm using an MVC framework...
Frameworks like Laravel do help. You have controllers and models for flow and logic. And then views for the presentation layer.
You create a controller for a specific piece of functionality. Like a pages controller to look after static pages for example.
That means you have no single responsibility issues there.
Likewise, the models you create support a controller. The Post model will link up with your Posts controller for example.
All good, no issues.
What about when you start adding custom classes?
A class should only have one reason to change...
What does that mean? It means that your classes should encapsulate one set of functionality.
If the spec for that functionality changes, then the class will need to change.
That sounds easy enough.
In practice, it can be much harder.
You've added a class to do some extra work. and that class provides functionality all around your build.
It's easy to keep adding code as the requirements develop. So that, in the end, you have a monolith that's difficult to test and maintain.
Break up the god classes
You can re-focus a class by separating out the functionality.
That does mean you will have more classes.
But it also means you'll have more manageable code.
Throwing more and more code into a class will mean you end up with god classes.
These classes might have hundreds of lines of code in them. And now you have a maintenance nightmare.
So, break 'em up.
oh, and comment your code too.
A word of caution
Before you go moving actions/methods around make sure you've understood the concept.
What Bob Martin was saying means this:
- Keep things together that change for the same reasons
- Separate those things that have different reasons to change
So, I should amend my previous comment to: break 'em up if they don't change for the same reason.
Most web coders will code well organised controllers, models and views. Frameworks make it trivial to achieve that.
When we are developing multi-layered apps, it's easy to end up building god classes. Too much code that doesn't change for the same reason.
So, It's worth keeping the single responsibility principle in mind as you code.