Controllers grow fat during the project lifetime fast. They are very easy to create and just as difficult to prevent once the project has gone live. You should keep controllers to a minimum to ensure they are exchangeable and represent no business logic.
Here are 4 tips on how to keep you code free of fat controllers.
- Avoid coding in controllers from the start
In crunch times and prototyping starting to code right in controllers doing everything there is tempting. During the process you are likely to call lots of various services, send mails, and possibly call some web services, forms and any other logic. You can implement some short-time requirements this way, but your code will be losing its maintainability and testability with every new line. That’s why when a new feature needs implementation, coders should refrain from creating a new controller – instead, it’s better to create a class and start afresh from scratch. If another service is needed, inject it. Your dependencies will suggest when to split your class up.
- Use the principle of single responsibility for controller actions, too
The single responsibility principle today is widespread and well-used, however not in controllers. You should make sure each controller action has no more than one responsibility. After refactoring your code so that each action is responsible for only one thing and made easy to understand, though your code may now look a bit bloated than before, after the complete optimization of the controller it’s going to look different.
- Extract or avoid shared methods at all
When an already existing controller includes shared methods, they should be moved to new classes. First, create a new service, cut and paste your original method content. Then, analyze the dependencies in this code to inject them. Next, this service with its dependencies should be defined in the container. Now the service is all ready to be used in your shortened controller. To ensure backwards compatibility and minimize the time of refactoring, the new service has to be called in its initial controller method.
- Go TTD
After you complete the previous steps, your code will get more testable, too. Test-driven way needs producing testable code fast and painlessly. In the result developers doing TDD automatically write code not located in the controllers. Only when the code needs execution from the web, it’s made accessible in controllers by means of services.
To sum it up, you should always aim to write as less programming code as possible in a controller. If you have to deal with already existing fat controllers, minimize them as much as possible.