Here’s a counterpoint to the currently popular view of “fat controllers are bad”, and the current fad of everyone and their cousin implementing service layers:
You don’t need one. Fat controllers are okay too.
Why you don’t need a service layer
A service layer is an additional level of complexity in your application.
Remember the good ol’ KISS principle? Keep it simple, stupid.
There’s a lot of code in your controllers. Who cares? It’s easy to see what’s going on if you’ve structured them logically into actions and maybe a helper function or two if needed.
If you were to include a service layer, it would…
- Cause a higher cognitive overload: It’s more difficult to see what’s going on and where, and to remember how things work without having to check
- And add another layer of indirection – the only thing you can’t solve by adding more layers of indirection is having too many layers of indirection, so don’t add unnecessary ones.
You could say that having a service layer would make things easier to unit test. But you’re going to test your controllers anyway, right?
So go right ahead, start with fat controllers!
Start with fat controllers?
You may have noticed that I said “start with” fat controllers.
So what does this really mean?
It’s fine if you code your things in the controllers, but there comes a point when you should stop that.
The moment you realize you’re duplicating your code, stop and refactor.
This is one of the very basics of software engineering: Avoid duplication by creating functions and classes.
However, you don’t necessarily need to do this prematurely – Similar to prematurely optimizing, you should avoid creating classes or code that isn’t necessary.
This isn’t to say you should never start with a service layer – There are various reasons why you might want to start with it, such as when doing test-driven development or when you already know you need to use the functionality in more than one place in the future (for example if you also need a command-line script).
What I am saying is that you should not go and write a service layer just because you can or just because the internet says you should.
Also note that you can have other abstractions besides the service layer. For example if you use ORM, you can often utilize domain objects to avoid ending up with a huge mess even if you don’t have a service layer.
So it’s fine if you don’t have a service layer in your simple application.
Don’t put too many layers in place in an application that doesn’t need them – it just becomes more complex than it has to. You can always change it later if it grows beyond the point.
If you’re working on an application which is large, having a service layer is definitely advantageous for various reasons, like testability and reduced code duplication.
Always think “Do I really need this?” before doing something – Remember the YAGNI principle.