Business logic in MVC [closed]
Asked Answered
P

10

208

I have 2 questions:

Q1. Where exactly does "business logic" lie in the MVC pattern? I am confused between Model and Controller.

Q2. Is "business logic" the same as "business rules"? If not, what is the difference?

It would be great if you could explain with a small example.

Perren answered 11/12, 2010 at 8:32 Comment(0)
S
190

Business rules go in the model.

Say you were displaying emails for a mailing list. The user clicks the "delete" button next to one of the emails, the controller notifies the model to delete entry N, then notifies the view the model has changed.

Perhaps the admin's email should never be removed from the list. That's a business rule, that knowledge belongs in the model. The view may ultimately represent this rule somehow -- perhaps the model exposes an "IsDeletable" property which is a function of the business rule, so that the delete button in the view is disabled for certain entries - but the rule itself isn't contained in the view.

The model is ultimately gatekeeper for your data. You should be able to test your business logic without touching the UI at all.

Schizomycete answered 11/12, 2010 at 8:45 Comment(13)
Thanks for the example. For the admin's email entry (controlling whether it can be deleted or not), can we not control that using our controller ?Perren
@mud what if we devide our model into two more layers i.e service layer and repository...service layer is responsible for business logic and repository is responsible for data layer...?Daron
@Schizomycete that means Business Logic is contained in the controller?Tuner
@Gauger in his answer states Mud told you that the business rules go into the model.That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.. Could you say if this statement is right or wrong?Isatin
I am very sorry that I didn't get answer from you to my question.Isatin
@PeterMatisko "Models should only carry data." You're not understanding what M means in "MVC". V is purely presentation. C is glue between presentation and model. (In fact, the "VC" are often thought of together as being the presentation layer, and popular variations of MVC like MVVM -- Model View Viewmodel -- make that even clearer.) The M is everything else: all the data and logic of your application. You can segregate data and business logic within this layer, and you can call the data portion of this layer your "model", but that's not what the "M" in "MVC" is referring to.Schizomycete
@Schizomycete I may agree, but .. typically in laravel, people then throw everything into the controllers or models. Bad bad architecture. In my opinion MVC is just not enough, it doesn't speak explicitely about business logic and where to put it. And I see the mess in majority of the laravel examples i meet online.Scratchboard
@PeterMatisko "in laravel, people then throw everything into the controllers or models. Bad bad architecture." Bad how? Be specific. "V" means "view". Everything that's not a view necessarily goes in "M" or "C". "MVC is just not enough, it doesn't speak explicitely about business logic and where to put it" Sure it does. "M" is the model of your application, which is your data, the business logic around it, and anything and everything else that's not presentation. "V" and "C" are presentation layer, user input and output.Schizomycete
@Schizomycete The problem is, that laravel calls a 'Model' just a data carrier. When tutorials say that Laravel uses MVC and then you see that 'Model' has a very specific purpose, then you end up with no clue where to put the business logic. And the only reasonable place is the controller, which is not good. I am not making this up, I just commented on typical laravel projects(and tutorials) that i often see.Scratchboard
@PeterMatisko "laravel calls a 'Model' just a data carrier" That's irrelevant. There is no "laravel" tag on this page. That's not what model means in almost any other computer science context, and certainly not in the model-view-controller pattern where it refers to the domain model. See Fowler or any other authority you respect. Wikipedia: "the model directly manages the data, logic and rules of the application". So your comment "this is extremely bad answer" is wrong. I expected at some point for you to say "I was mistaken", but it appears you keep trying to justify your comment instead.Schizomycete
@Schizomycete I admin my mistake, considering the definition of MVC you are refering to. However, I still believe, that this concept is widely misunderstood and produces poor design especially in laravel code that I work with on a daily basis. The note about this thread not being about laravel is taken.Scratchboard
@Schizomycete I deleted my original comment, as it was meant to be mostly about laravel misused terminology.Scratchboard
@Schizomycete Thank you for standing your ground. People get too literal when they hear "business logic in the Model". Suddenly, Eddie Murphy's line about a "Banana in the tailpipe" in Beverly Hills Cop comes to mind. Obviously, business logic, data access, and service usage will be contained in various classes. You can say then that a Model is not monolithic. It is modular and has layers. The interplay between input data, input validation, state data (database), business logic, and services must be resolvable in some common sense context. The Model is where this interplay occurs.Housebreaking
G
221

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.

Gauger answered 12/6, 2013 at 12:27 Comment(8)
+1 for listing correctly the difference between mvc and n-tier app. Most of enterprise apps I develop have n-tier and uses mvc as a presentation layer only.Vanderbilt
Lets say 1) View Models in MVC (Presentation Layer) 2) Some C# Technologies (Business Layer) for Authorized Transactions, Core Business Rules Logic. 3) Repository and Unit of work in (Data Access Layer) Please guide some technologies (or Best Practiced Patterns) that can be used to build Business Layer which should freedom to allow and expose model, repository to access from controller in presentation layer (Upper Layer). Basically I believe Add, Delete, Update & its Combination as Business Logic and should be kept under Transactions. Kindly spread some additional light on this.Ginglymus
Hi Rahul, if i understand you correctly, then your're right. CRUD operations are basically atomic parts of business transactions. I personally prefer using a powerful OR mapper like Hibernate as a repository instead of building my own. That is because hibernate already implements the unit of work pattern internally. Also I usually put business transactions into seperate business services.Gauger
For the view model i can give you the following example: Just image you have a GUI with a dual-list-view in it. This dual-list-view uses a dual-list-view-model as its datamodel. This datamodel is just a composition of two simple lists. So the dual-list-view-model is dependent on the implementation of the presentation layer as it is not part of your domain model, unlike the two simple lists that are used to create the view-model. Depending on the GUI you want to create, there are several cases where you might want to bind a view specific model to a view instead of your domain model.Gauger
The business rules / logic part is a bit tricky to explain. In order to start any data-processing you call a method from one of your services. That means you basically start a transaction. If this method contains the business logic than it is called a "transaction script". That's usually a bad thing as it is hardly reusable. It would be better if this method calls the business logic of your domain model. This means that your domain model has to be desinged in a way that it is able to contain the business logic. This domain-driven approach will not work with an incomplete or wrong domain model.Gauger
Sometimes I think people are being a bit too literal about "business logic" in the Model. No one is suggesting that one should create a bunch of methods on a child of a Model that house the true business logic of an application. Conceptually, that logic will naturally be housed in relevant classes (cumulatively, a business layer, if you will). The question that most people are driving at is should they utilize their classes that do the business logic and data access from a Model. The interplay between various classes, database data, and service access must be resolved somewhere! :-)Housebreaking
MVC is not the presentation layer of 3-tier architecture, both things are totally different. You MAY define your presentation layer using MVC if you want, but you also may define your presentation layer in a totally different way. Finally, you can get rid of 3-tier architecture and define the whole system following the MVC pattern, that's totally fine. In doubt, just keep in mind the mantra: "Keep it simple, stupid".Controversy
This should be the accepted answerBedight
S
190

Business rules go in the model.

Say you were displaying emails for a mailing list. The user clicks the "delete" button next to one of the emails, the controller notifies the model to delete entry N, then notifies the view the model has changed.

Perhaps the admin's email should never be removed from the list. That's a business rule, that knowledge belongs in the model. The view may ultimately represent this rule somehow -- perhaps the model exposes an "IsDeletable" property which is a function of the business rule, so that the delete button in the view is disabled for certain entries - but the rule itself isn't contained in the view.

The model is ultimately gatekeeper for your data. You should be able to test your business logic without touching the UI at all.

Schizomycete answered 11/12, 2010 at 8:45 Comment(13)
Thanks for the example. For the admin's email entry (controlling whether it can be deleted or not), can we not control that using our controller ?Perren
@mud what if we devide our model into two more layers i.e service layer and repository...service layer is responsible for business logic and repository is responsible for data layer...?Daron
@Schizomycete that means Business Logic is contained in the controller?Tuner
@Gauger in his answer states Mud told you that the business rules go into the model.That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.. Could you say if this statement is right or wrong?Isatin
I am very sorry that I didn't get answer from you to my question.Isatin
@PeterMatisko "Models should only carry data." You're not understanding what M means in "MVC". V is purely presentation. C is glue between presentation and model. (In fact, the "VC" are often thought of together as being the presentation layer, and popular variations of MVC like MVVM -- Model View Viewmodel -- make that even clearer.) The M is everything else: all the data and logic of your application. You can segregate data and business logic within this layer, and you can call the data portion of this layer your "model", but that's not what the "M" in "MVC" is referring to.Schizomycete
@Schizomycete I may agree, but .. typically in laravel, people then throw everything into the controllers or models. Bad bad architecture. In my opinion MVC is just not enough, it doesn't speak explicitely about business logic and where to put it. And I see the mess in majority of the laravel examples i meet online.Scratchboard
@PeterMatisko "in laravel, people then throw everything into the controllers or models. Bad bad architecture." Bad how? Be specific. "V" means "view". Everything that's not a view necessarily goes in "M" or "C". "MVC is just not enough, it doesn't speak explicitely about business logic and where to put it" Sure it does. "M" is the model of your application, which is your data, the business logic around it, and anything and everything else that's not presentation. "V" and "C" are presentation layer, user input and output.Schizomycete
@Schizomycete The problem is, that laravel calls a 'Model' just a data carrier. When tutorials say that Laravel uses MVC and then you see that 'Model' has a very specific purpose, then you end up with no clue where to put the business logic. And the only reasonable place is the controller, which is not good. I am not making this up, I just commented on typical laravel projects(and tutorials) that i often see.Scratchboard
@PeterMatisko "laravel calls a 'Model' just a data carrier" That's irrelevant. There is no "laravel" tag on this page. That's not what model means in almost any other computer science context, and certainly not in the model-view-controller pattern where it refers to the domain model. See Fowler or any other authority you respect. Wikipedia: "the model directly manages the data, logic and rules of the application". So your comment "this is extremely bad answer" is wrong. I expected at some point for you to say "I was mistaken", but it appears you keep trying to justify your comment instead.Schizomycete
@Schizomycete I admin my mistake, considering the definition of MVC you are refering to. However, I still believe, that this concept is widely misunderstood and produces poor design especially in laravel code that I work with on a daily basis. The note about this thread not being about laravel is taken.Scratchboard
@Schizomycete I deleted my original comment, as it was meant to be mostly about laravel misused terminology.Scratchboard
@Schizomycete Thank you for standing your ground. People get too literal when they hear "business logic in the Model". Suddenly, Eddie Murphy's line about a "Banana in the tailpipe" in Beverly Hills Cop comes to mind. Obviously, business logic, data access, and service usage will be contained in various classes. You can say then that a Model is not monolithic. It is modular and has layers. The interplay between input data, input validation, state data (database), business logic, and services must be resolvable in some common sense context. The Model is where this interplay occurs.Housebreaking
H
80

The term business logic is in my opinion not a precise definition. Evans talks in his book, Domain Driven Design, about two types of business logic:

  • Domain logic.
  • Application logic.

This separation is in my opinion a lot clearer. And with the realization that there are different types of business rules also comes the realization that they don't all necessarily go the same place.

Domain logic is logic that corresponds to the actual domain. So if you are creating an accounting application, then domain rules would be rules regarding accounts, postings, taxation, etc. In an agile software planning tool, the rules would be stuff like calculating release dates based on velocity and story points in the backlog, etc.

For both these types of application, CSV import/export could be relevant, but the rules of CSV import/export has nothing to do with the actual domain. This kind of logic is application logic.

Domain logic most certainly goes into the model layer. The model would also correspond to the domain layer in DDD.

Application logic however does not necessarily have to be placed in the model layer. That could be placed in the controllers directly, or you could create a separate application layer hosting those rules. What is most logical in this case would depend on the actual application.

Heritor answered 28/8, 2011 at 16:40 Comment(2)
This is very true! There are two models here your View Model and Your Domain Model. I think its almost unfortunate that the layout of MVC projects leads novice developers to believe that they should just cram their code into the View Model.Pangolin
Found your answer more acceptable and understandable. Thanks.Rear
N
34

A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.

Navada answered 11/12, 2010 at 8:46 Comment(0)
R
24

As a couple of answers have pointed out, I believe there is some some misunderstanding of multi tier vs MVC architecture.

Multi tier architecture involves breaking your application into tiers/layers (e.g. presentation, business logic, data access)

MVC is an architectural style for the presentation layer of an application. For non trivial applications, business logic/business rules/data access should not be placed directly into Models, Views, or Controllers. To do so would be placing business logic in your presentation layer and thus reducing reuse and maintainability of your code.

The model is a very reasonable choice choice to place business logic, but a better/more maintainable approach is to separate your presentation layer from your business logic layer and create a business logic layer and simply call the business logic layer from your models when needed. The business logic layer will in turn call into the data access layer.

I would like to point out that it is not uncommon to find code that mixes business logic and data access in one of the MVC components, especially if the application was not architected using multiple tiers. However, in most enterprise applications, you will commonly find multi tier architectures with an MVC architecture in place within the presentation layer.

Retrogress answered 25/8, 2017 at 13:13 Comment(4)
Best answer on the matter. Should be voted higher. The worst answer is marked as accepted.Scratchboard
Best answer.. no doubtSanguinaria
Does this depend on the size of the data and application? For a small app, I'm guessing all the logic could go into models without any confusion. If so, what is the threshold of size to start separating into a separate layer?Gunfight
@Gunfight That is a good question. There is a lot of confusion that surrounds these architecture type questions and lots of opinions as well. So nobody can answer definitively but IMO, yes it does depend on the size of the app. Small apps very commonly have all the logic in the models. So what's the threshold for separating into a separate layer? Probably the point in time when the dev with the squeakiest wheel starts complaining about confusion and has the power to make change. This could be at the beginning of a small project or the middle of a large project. As they say, it all depends.Dawn
M
15

This is an answered question, but I'll give my "one cent":

Business rules belong in the model. The "model" always consists of (logically or physically separated):

  • presentation model - a set of classes that is well suited for use in the view (it's tailored toward specific UI/presentation),
  • domain model - the UI-independent portion of the model, and
  • repository - the storage-aware portion of the "model".

Business rules live in the domain model, are exposed in a presentation-suitable form to the "presentation" model and are sometimes duplicated (or also enforced) in the "data layer".

Matthias answered 15/7, 2013 at 3:45 Comment(0)
G
7

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

Gnathous answered 3/2, 2017 at 18:44 Comment(1)
Would you clarify this statement? "A Model contains the data that comes from the business layer that passes to the view to display. "Housebreaking
T
2

Q1:

Business logics can be considered in two categories:

  1. Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.

  2. More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).

The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).

See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.

The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).

Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).


Q2:

Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:

business rules ⊂ business logics

Toxicogenic answered 16/2, 2016 at 17:45 Comment(0)
S
2

Why don't you introduce a service layer. then your controller will be lean and more readable, then your all controller functions will be pure actions. you can decompose business logic as you much as you need within service layer . code reusability is hight . no impact on models and repositories.

Supportable answered 20/9, 2019 at 6:12 Comment(0)
Q
-5

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

Qktp answered 14/3, 2013 at 15:22 Comment(2)
If you put business rules in controller and you have many, many actions - are you going to replicate the business rule many, many times? No. You'll separate it in a helper method or a class of some sort. Put that "thing" in the model, where it belongs.Matthias
MVC is not an application pattern for CRUD database operations (although it can be used that way) therefore Model cannot be "code for CRUD database operations". The model defines the entities of the application, including the data and the business rules. The controller coordinates the interaction between the view and the model. The view is the user interface exposing the model and the available operations in the models exposed by the controller.Ineradicable

© 2022 - 2024 — McMap. All rights reserved.