Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - Should business logic exist in controllers?

Derik Whitaker posted an article a couple of days ago that hit a point that I've been curious about for some time: should business logic exist in controllers?

So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.

like image 469
Kevin Pang Avatar asked Oct 24 '08 20:10

Kevin Pang


1 Answers

Business logic should really be in the model. You should be aiming for fat models, skinny controllers.

For example, instead of having:

public interface IOrderService{     int CalculateTotal(Order order); } 

I would rather have:

public class Order{     int CalculateTotal(ITaxService service){...}         } 

This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services.

This would make your controller look something like:

public class OrdersController{     public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...}      public void Show(int id){         ViewData["OrderTotal"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService);     } } 

Or something like that.

like image 188
jonnii Avatar answered Oct 05 '22 01:10

jonnii