Design Patterns – How Much Business Logic Should Exist in the Controller Layer?

design-patternsmvc

Sometimes we have some business logic represented in the controller code of our applications. This is usually logic that differentiates what methods to call from the model and/or what arguments to pass them.

Another example of this is a set of utility functions that exist in the controller that may work to format or sanitize data returned from the model, according to a set of business rules.

This works, but I am wondering if its flirting with disaster. If there is business logic shared between controller and model the two layers are no longer separable, and someone inheriting the code may be confused by this unevenness in location of business logic related code.

My question is how much business logic should be allowed in the controller and in what circumstances, if any?

Best Answer

Ideally none

But that's not always possible. I can't give you hard numbers like 20% or 10 lines, that is subjective to the point it can't be answered. I can describe how I use design patterns and circumstances that necessitate bending them slightly.

In my mind it's entirely up to the purpose of the application. Building a simple REST api to post to? Forget about clean separation or even a pattern. You can churn out a working version in under an hour. Building something bigger? Probably best to work on it.

Building individually contained systems is the goal. If you start writing business logic that is specific to how two systems interact that is a problem. Without looking further into it I can't give an opinion.

Design patterns are molds, some like to strictly adhere to them on the basis of principal and well-written code. Strictly adhering to a pattern probably won't give you bad code, but it could take more time and cause you to write much more code.

Design patterns are flexible, adjust them to suit your needs. Bend them too much and they break though. Know what you need and pick a design pattern closest to that.