MVC: Where to put business logic?

Andrius Naruševičius picture Andrius Naruševičius · Sep 1, 2013 · Viewed 62.3k times · Source

First of all, I have seen many questions of this, but not enough reasoning behind that. If my question is not good enough and should be removed I'll understand.

I have taken a look at, for example, this and a 45+ voted up answer says he advises you to put the business logic in the model, which sounds pretty logical.

However, my first large project I have done with all my BL fully in the controllers, because I didn't question these things and looked how it is done in the AccountController which is the automatically added if you choose MVC with form authentication. All the methods look pretty stuffed with BL. Or maybe it is the least amount of code that was possible to be added and I am overlooking things?

A person on youtube asked me whether he is right by putting all the logic into his models and at first I was no! Then I started thinking that maybe he was right!?

So, after all, where do I put my business logic? If it is in models classes, then, how much code should be considered a healthy amount in a method which is in controller? One line to call some method from the model in a controller at most and then a return to the view?

Answer

Ferruccio picture Ferruccio · Sep 2, 2013

I prefer to put domain logic in the model for a couple of reasons.

  1. The model should have no UI code in it and thus be easier to test. Whenever possible, I like to have a fully working (meaning complete test coverage) model before writing any UI code. The controller can trust that the model is doing the right thing and just deal with UI concerns.

  2. If you put domain logic in a controller, it's not as easy to share between different apps, or even between different controllers.