But this post isn't about that. This post is inspired by the rules, combined with observations I’ve made about the way many developers approach software design in general. This particularly applies in the ASP .Net world. It’s as if they’re following their own set of rules.
Here are the rules in all their glory:
- For each entity of your system, create a class suffixed with the following: Controller, Service and Repository. Service and Repository should also have header interfaces. For example, OrdersController, IOrdersService, OrdersService, IOrdersRepository and OrdersRespository
- Controller methods must call a correspondingly named method on a Service interface. That is, OrdersController.GetOrder method must call IOrderService.GetOrder.
- Service methods must contain a line that calls the corresponding Repository interface’s method. That is, OrdersService.GetOrder must call IOrdersRepository.GetOrder. They may also call other service classes but nothing else.
- Repositories must only expose CRUD methods and be implemented using an ORM that already implements the Repository pattern such as Entity Framework.
- Testing anything but the Service is forbidden. Even if the controller appears perfectly unit-testable you must resist the temptation. Liberally use mocks of those header interfaces you created earlier.
There you have it. Just follow these rules, and you are now able to write perfect enterprise software. This would never end in a tangled mess lacking cohesion.
You can even say you’re doing Domain Driven Design now because you have Repositories and Service Layer and TDD because you have unit tests. Think of it as a bullet-proof vest, no one ever gets fired for writing code like this.
These are a one-size-fits-all so apply them everywhere. Don’t forget to enforce the rules in all your code reviews!