Reputation: 156
I recieved an mvc4 application from my friend in which I will add some functions. but I found that he use controllers with more Than 6000 line of code. I want to know what's the ideal way to develop MVC4 application.
means to have many controllers with little number of line code in each one. or to have little number of controllers with big number of line code.
Upvotes: 1
Views: 174
Reputation: 3703
There definitely isn't a generic solution to this problem, however you can reduce the number of “lines” within a controller by using repositories which will also enable you to make use of the dependency injection pattern.
Dependency injection will also help with unit testing. The repository separates the logic into a separate (replaceable) class.
Searching these terms will provide lots of information (unfortunately far too much to put all the information in a SO question) – but here is some code that will help you in the right direction:
Create an interface to define the repository
public interface IGenericControllerRepository
{
MyModel[] ComplexMethod();
}
Controller class:
public class GenericController : Controller
{
private IGenericControllerRepository repository;
public GenericController() : this(new GenericRepository()) { }
public GenericController(IGenericControllerRepository genericRepository)
{
this.repository = genericRepository;
}
// GET: /controller
public ActionResult Index()
{
MyModel[] m = repository.ComplexMethod();
return View("Index", m);
}
}
Repository Class
public class GenericRepository : IGenericControllerRepository
{
public MyModel[] ComplexMethod()
{
// do work here
}
}
It is hard to judge if you should split your controller into smaller ones as that really depends on the number of methods rather than the number of lines ( for example you could have a few methods with hundreds of lines ) in which case separating them into another controller won’t achieve a desired outcome. Your controllers should be split into “application logical” containers.
Upvotes: 1
Reputation: 119
I think your friend maybe put the business logic into the controllers. You should put the business logic to other class, folder or projects.
Upvotes: 0
Reputation: 6152
I don't think there's a 'right' answer to this, especially without any concrete examples.
Just think about maintainability going forward. A monolithic controller with multiple thousands of lines of code is likely to be much more difficult to understand (and therefore maintain) than a smaller, more targeted controller.
Also I would look carefully at the kind code that goes into your controller. The controller is there to link your models to your views and is not the best place for business logic code; I would personally put any significant business logic into some kind of repository that the controller references.
Upvotes: 1