Refactoring MVC controller code. Controller or model
I have a lot of code in a controller and I'm not sure where to put it. First I re-factored it so that it is DRY but still in the controller开发者_Python百科.
What is a good guideline to follow when re-factoring code, such as when to move something to a model and when to keep something in a controller?
Your model generally should contain no business logic. If it does, extract that model out into a ViewModel
and the only logic in it should be your display related code. Any business methods should exist in a separate class. Some prefer to use ViewModels
all the time instead of general overall models (ex. CustomerEditViewModel
instead of just a Customer model
).
The controller should be very lightweight and should not have data access code in it. I generally call a repository method (Repository Pattern) to easily load data and the Facade Pattern as a gateway to any business methods that are performed.
For instance, rather than having data loading code, some calculations, and some saving code, this could all be put into a facade class that takes a model or customerId
and does something like:
CustomerRepository repository = new CustomerRepository(); Customer customer = repository.GetCustomer(customerId); // call some business methods, assign data, etc. .. .. // now save repository.SaveCustomer(customer);
Your repository class is usually coded to an interface; this makes stubbing out/mocking these classes to load 'fake' data extremely easy and also decouples your controller and facade from linking directly to a concrete implementation of a class, but instead to an interface.
The controller should primarily contain coordination code. So if, by some chance, you have code performing some business or domain function you could move that. I tend to use application services or simple tasks. Something like IImageService or IDocumentService (although the implementations can become quite bloated). I also like using individual tasks such as ILoginTask.
The implementations are then injected (I use Castle Windsor with a custom controller factory).
Just my 2c --- HTH
精彩评论