66

The main idea behind OOP is to unify data and behavior in a single entity - the object. In procedural programming there is data and separately algorithms modifying the data.

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively. In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

Random42
  • 10,370
  • 10
  • 48
  • 65
  • 11
    Why would they need to be in the same logical entity? You haven't stated why that would be advantageous, or why OOP would dictate this arrangement. – Robert Harvey Oct 10 '12 at 14:40
  • For the same reasons data and behavior are placed in a single entity in OOP. – Random42 Oct 10 '12 at 14:41
  • 27
    Well, the business logic goes in the model, not the controller. The controller is really just a go-between to glue together the View and the Model. So in the model, you have data and behavior in the same place. – Robert Harvey Oct 10 '12 at 14:44
  • 3
    What? Unifying data and behavior together is exactly what OOP is all about. – Andy Oct 10 '12 at 15:48
  • 3
    OOP is about separating implementations from interfaces. Interfaces have more to do with behavior, and implementations more with data (which is why data tends to be hidden). So OOP is not about unifying data and behavior but separating them. – Kaz Oct 10 '12 at 17:42
  • 5
    Anyway, you don't want to stuff all data and behavior into one class. OOP programs use more than one class to create frameworks of objects. And anyway, if something is "anti-OOP", that could be a good thing. OOP is not the be-all end-all. OOP downright sucks. It's time to get over OOP. – Kaz Oct 10 '12 at 17:43
  • @Robert Harvey Please post that comment as an answer in order for me to accept; while it was not designed with OO approach in mind this proves the fact that MVC does not break OO basic rule. Initially I was mislead by the fact that the controller changes the state of the model. – Random42 Oct 10 '12 at 18:37
  • 2
    @JeffO: MVC is not a GOF pattern. http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller#History – Robert Harvey Oct 10 '12 at 19:56
  • @Kaz It is about unifying data and behavior in the portability sense. The fewer unnecessary external dependencies an object has, the easier it is to use elsewhere or modify to work differently when placed in a different context. I think I would like OOP less if I came up in a language that assumes you'll be using it exclusively. OOP + functional + closures and dynamic types/general mutability bordering on the obscene has been working out pretty great for me personally. – Erik Reppen Oct 11 '12 at 00:33
  • Read about information hiding (one of the key principles to OO): http://en.wikipedia.org/wiki/Information_hiding – dukeofgaming Oct 16 '12 at 20:39
  • 1
    @ErikReppen How many classes have you written so far that's easy to tear out of its current context, and use it elsewhere, without forcing you bring the entire framework that surrounds it? Class reuse is a myth... – Calmarius Jul 04 '13 at 14:22
  • @Calmarius I won't claim every single class/constructor I write is its own island, nor should they be in all cases necessarily but I'm frequently able to pop old code out and re-use in new code with zero to minor modification. It should not seem like a myth to you unless you mean you don't see it much in the wild which I can sympathize with. Most devs simply aren't getting the basics of OOP. The Extreme Programming training industry and a lot of other stuff embraced by Java and C# wholesale as communities aren't helping, IMO. – Erik Reppen Jul 05 '13 at 15:34
  • @ErikReppen Hiding your data in a class doesn't change its dependencies. If your `Foo`'s `frobnicate` function needs a `Bar`, it's going to need a `Bar` regardless of whether `Foo`'s fields are public or private. What changes is that *other* code can't develop dependencies on `Foo`'s internals, and if *that's* what you're trying to say, then you essentially agree with @Kaz. – Doval Mar 18 '14 at 15:06
  • @Doval I wasn't thinking data fed to an object's API when I said dependencies. I was thinking more of something that builds objects within from external user-defined classes. Once you start referencing stuff defined on the exterior, that has to travel with your class when you want to move it and you're no longer portable. If I were required to write code in a statically typed language my immediate instinct would be to only feed generic core language structures to object APIs or rely on interfaces to keep things generic between classes. Otherwise it might as well be funcs calling funcs. – Erik Reppen Mar 27 '14 at 03:55
  • @ErikReppen If you could move the class, what's stopping you from also moving the other types it depends on? You're not going to get very far relying only on primitive types. – Doval Mar 27 '14 at 03:58

14 Answers14

76

MVC works at a much higher level of abstraction than single objects, and in fact each of the three (model, view and controller) will typically consists of many objects that each have both data and behavior.

That objects which encapsulate data and behavior are a good fundamental building block for programs in general doesn't mean it's the best pattern at all levels of abstraction and for all purposes.

Michael Borgwardt
  • 51,037
  • 13
  • 124
  • 176
  • Object-Oriented approach can scale in level of abstraction; see for example the reason behind Domain Driven Design which appeared because the classical layered architecture is not OOPish but rather procedural. This happens at a higher level of abstraction than MVC. – Random42 Oct 10 '12 at 14:46
  • 6
    @m3th0dman: You're speaking in broad, sweeping generalities. How about discussing specifics, like how MVC eliminates the spaghetti-code nightmare that is Winforms or Webforms? – Robert Harvey Oct 10 '12 at 14:48
  • 3
    @m3th0dman: that's a pretty simplistic characterization of DDD. – Michael Borgwardt Oct 10 '12 at 14:51
  • 1
    @RobertHarvey To be sure you're counter-point of why MVC is good because it does away with the spaghetti is not really at contest here. I agree but I tend to see MVC implemented in the procedural pattern as well. So I think it's a relevant question to ask, or rather- maybe the question to ask is "How often do people implement MVC procedurally?" – Jimmy Hoffa Oct 10 '12 at 14:59
  • 1
    @Robert Harvey The purpose of the question is not about how good or bad MVC is; it is about the fact that is based or not on OO principles. – Random42 Oct 10 '12 at 18:24
  • @m3th0dman: Yeah, I got that. Have a look at my comment I posted below your question. Most of the answers here pretty much hammer the point that your definition is not a hard and fast rule: data and behavior *do not* always have to be encapsulated in the same object for it to still be considered OOP. – Robert Harvey Oct 10 '12 at 18:25
  • @Michael Borgwardt The purpose of that comment was not the characterization of DDD but rather an example of an OO approach at a level of abstraction higher than classes. – Random42 Oct 10 '12 at 18:25
  • In the context of this discussion, I'd say that MVC is simply a way to apply the SRP; nothing un-object-oriented about that, whatsoever. – Daniel B Oct 11 '12 at 08:41
74

OOP does not restrict interactions among objects that each have their own data and their own behavior.

Think of an ant and an ant colony analogy: behavior of an individual ant (run around all day, bringing food) is different from behavior of the overall colony (find the most desirable place, make more ants). The MVC pattern describes the desired social structure of an ant colony, while OOP guides the design of individual ants.

Sergey Kalinichenko
  • 17,393
  • 4
  • 57
  • 73
49

MVC is an exercise in Separation of Concerns, a UI architecture. It is a way to corral the complexity that can occur in user interfaces due to the presentation not being separated from the content.

In theory, all objects can have behavior that operate on the data they contain, and that data and behavior remain encapsulated. In practice, a given OOP object may or may not have logic that corresponds to its data, or may not have any logic at all (a Data Transfer Object, for example).

In MVC, the business logic goes in the model, not the controller. The controller is really just a go-between to glue together the View and the Model. So in the model, you can have data and behavior in the same place.

But even that arrangement does not guarantee strict data/behavior fusion. Objects containing only data can be operated on by other classes containing only logic, and this is a perfectly acceptable use of OOP.


I'll give you a specific example. This is a bit contrived, but let's say you have a Currency object, and that object has the ability to represent itself in any available currency, pegged to the dollar. So you would have methods like:

public decimal Yen { get { return // dollars to yen; } }
public decimal Sterling { get { return // dollars to sterling; } }
public decimal Euro { get { return // dollars to euro; } }

...and that behavior would be encapsulated with the Currency object.

But what if I wanted to transfer the currency from one account to another, or deposit some currency? Would that behavior also be encapsulated in the Currency object? No, it wouldn't. The money in your wallet cannot transfer itself out of your wallet into your bank account; you need one or more agents (a teller or ATM) to assist in getting that money into your account.

So that behavior would be encapsulated into a Teller object, and it would accept Currency and Account objects as inputs, but it would not contain any data itself, except maybe a bit of local state (or maybe a Transaction object) to help process the input objects.

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
  • And in what entity/package should the `Teller` be placed in? In the `Controller` from where the `Teller's` methods are called or in the `Model` because it's part of the business logic? – Random42 Oct 11 '12 at 06:44
  • `Teller` goes in the `Model`, although it could be called from the controller. It's part of the business domain. – Robert Harvey Oct 11 '12 at 14:21
  • I've always thought that using the Model for business rules makes MVC a semi-effective pattern. Using the Model for adapters to the real application, and having the controllers mediate between the adapters and the view is always much more effective in achieving SoC. – Yam Marcovic Oct 11 '12 at 16:14
  • @YamMarcovic: I'm not sure what you mean. The Model is kind of a catch-all; in practice, business rules are typically placed in their own service layer, but it's still considered part of the Model (you wouldn't encode specific business rules within an individual controller method, for example). You are right that the controllers are a go-between. – Robert Harvey Oct 11 '12 at 16:27
  • @RobertHarvey There are 2 ways to look at MVC. One is that the model encapsulates all business logic, and the other is that there is an application, and on top of it you add MVC components to make a user interface for that application. That UI is consisted of adapters to the application logic (models), different styles or mechanisms of showing data from the adapters (views), and controllers, which act as mediators. I've had good experience with the latter, while the first ultimately always creates tight coupling all around, in one way or another. – Yam Marcovic Oct 11 '12 at 18:06
  • @YamMarcovic: You'd have to post an example for me to get what you are talking about. The two scenarios you are describing merely looks like differences in terminology to me. My definition of "application" is software that already has a UI of some sort. If it doesn't have a UI, it's a "service" or a "library." – Robert Harvey Oct 11 '12 at 18:10
  • 5
    One thing I think most people are getting wrong about MVC just from reading up on it is overly broad assumptions about what "business logic" means. If you can't pop your model out and use it with minimal to no modification in a brand new app that's going to have the same business goals but a very different architecture via a controller with completely different application logic, you're doing it wrong IMO. There's still value in decoupling views from whatever mix of everything else you have, of course but C as a lightweight construct strikes me as missing a key point of separation. – Erik Reppen Oct 11 '12 at 22:23
  • Also, I'm really starting to wonder about DTOs. Certainly you have to transfer data at some key points but in our code base they're almost universally passed around through dozens of classes. They're like transient global objects which definitely does thwart a major goal of OOP IMO, which is to bind data and behavior for interacting with it at one point. If you need a DTO, it's because the data is being touched by a lot of hands and it's hard to tell where it went wrong without a compiler fail. I thought that was the yucky procedural code tendency OOP was meant to help us avoid. – Erik Reppen Jul 05 '13 at 16:04
  • @ErikReppen: Consider a situation where you have to transfer a customer data packet over the internet to some remote location. Nobody expects all the application behavior that pertains to a customer to be encapsulated in that data packet. Transferring data packets between classes in a program is really not all that different, from that perspective. That a class instance is encapsulating a collection of data only, and not behavior, does not invalidate its encapsulation benefit. – Robert Harvey Oct 31 '13 at 18:38
  • Strictly speaking if the Data is not encapsulated, then it's not OOP. With MVC the model properties are public for the views to read. This sounds more procedural to me than object oriented. – Ced Feb 20 '23 at 15:47
19

OOP is also about Separation of concerns, that is to separate different roles/responsabilities in different objects.

MVC separates into these components :

  • Model : the data and its business logic
  • View : representation of the data
  • Controller : coordination between the model and the view.

So these responsabilities are clearly distinct and should indeed be separated into multiple entities.

marco-fiset
  • 8,721
  • 9
  • 35
  • 46
  • It's true that the single responsibility principle is helpful in using OOP effectively, but I think it's a stretch to say that "OOP is also about the Single Responsibility Principle." That seems backward. – Caleb Oct 11 '12 at 15:02
  • @Caleb Yeah, I understand what you mean. Maybe it could be rephrased but you get the point. – marco-fiset Oct 11 '12 at 15:03
  • Single responsibility principle is not about separating technologies, else you could never log anything. Single responsibility principle is about the class `Product` only dealing with `Product`, it's really about subject – Ced Oct 23 '22 at 10:46
18

In the Model-View-Controller pattern the data and the logic/algorithms are placed in distinct entities, the model and the controller respectively.

Model and controller are two distinct roles. A model has both state and logic, and a controller has both state and logic. The fact that they communicate doesn't break the encapsulation of either one -- the controller doesn't know or care how the model stores its data, or what it does to the data when the controller retrieves or updates some part of it. The model doesn't know or care what the controller does with data that the model provides.

Think of it this way: if objects couldn't pass data back and forth without breaking encapsulation, you could really only have one object!

In an equivalent OOP approach shouldn't the model and the controller be placed in the same logical entity?

MVC is an OOP approach -- specifically, it's a recipe for deciding how to use objects to organize a program effectively. And no, the model and controller shouldn't be the same entity. A controller allows separation between model and view. Keeping model and view independent of each other makes them both more testable and more reusable.

Caleb
  • 38,959
  • 8
  • 94
  • 152
  • I would hope that the controller has logic but little to no state. What sort of state are you thinking the controller has? – Matthew Flynn Oct 10 '12 at 17:12
  • 1
    @MatthewFlynn For starters, a controller needs to know about the view and the model. Beyond that, it may depend on what particular flavor of MVC we're talking about, but in general a controller might keep state related to *how* information should be displayed (e.g. current selection), whereas the model deals with *what* information is displayed. – Caleb Oct 10 '12 at 17:28
  • Shouldn't "current selection" also be part of the model, not the controller? (I'm not an MVC expert, so it's an honest question). –  Oct 10 '12 at 17:49
  • 1
    @MattFenwick That's what I mean about the 'flavor'... Exactly what you store in the controller and what in the model is a matter of taste and convention. In Cocoa/Cocoa Touch, it's common to keep such things as current selection and even user preferences in the controller. MVC as used in some web frameworks may put nearly everything in the model and very little in the controller. YMMV. – Caleb Oct 10 '12 at 19:54
  • 4
    @MatthewFlynn Most will agree with you but IMO, people take business logic to be a broader category than it's supposed to be. The controller handles application logic which people often get confused with business logic. In an ideal separation of concerns, I should be able to re-use a model object in an entirely different app architecture serving the same business goals without modification to the business object. All the new application has to do is use the interface and do its own thing with data and transactions as-returned and processed. – Erik Reppen Oct 11 '12 at 01:07
  • 1
    @MattFenwick: Consider multi-user application. There an obvious point to draw the line between model and controller is that model handles the shared state and controller the local state. Current selection is local, so it goes in controller. – Jan Hudec Oct 11 '12 at 08:56
  • MVC is an OOP anti-pattern, but the lesser of evils. Another class should not know the internal details of another class. The controller class does exactly this is follows the "god class" anti-pattern. Life is not so simple to say one should never use anti-patterns. DI is also an anti-pattern, but has a very specific set of pro and cons that have been well studied and generally decided are worth the trade offs for certain situations. – Bengie Jul 17 '19 at 02:37
  • @Bengie That may be true in poor implementations, but there's no reason that a controller needs to know anything beyond the public interfaces of the model and view objects that it manages. Controllers do often talk directly to subviews, but typically an entire view graph is a controller's responsibility: don't confuse containment (e.g. a control inside some container) with implementation details. You could create a separate container view that manages the view graph and presents a single unified interface to the controller, but that provides little actual value. – Caleb Jul 17 '19 at 03:57
  • @Bengie Aren't you conflating DI with the service locator pattern ? – Ced Oct 23 '22 at 13:42
4

MVC is a pattern which describes a sensible way for objects to interact; it is not itself a meta-class. At that, OO is about describing behaviours and data of entities, and how said entities interact. It isn't about unifying the entire system into one massive object.

2

Controller does not represent the behavior of a model. Controllers altogether represent the behavior of the whole application _ what a user can do and what a user can see.

It is wrong to view controllers and models as one. They have different purposes, different semantics and thus shouldn't be unified in one object.

superM
  • 7,363
  • 4
  • 29
  • 38
2

The model layer is not merely data any more than the controller layer is merely logic.

The controller layer will have a complete collection of objects for its purposes. There will be objects for receiving input from the view, and from transforming that input into a form the model can process. The Struts Java framework has a good example of this in its Action/Form model. The Form is populated with input from the user, and then passed to the Action. The Action takes that data and uses it to manipulate the model.

In the same way, the Model layer doesn't consist entirely of data. Take a User object, for example - you may need code that gets a user from a database, or code to associate a User with an Order, or to validate that the User's address is within the area your company services...you get the picture. This is not controller logic. It's business logic, and it's led many to split their Model layer into several layers such as Service or Manager layers for business logic, a DAO (Database Access Object) layer for database access, and others.

MVC isn't a method for organizing individual Model operations. It works at a higher level than that - it's a method for organizing how the application is accessed. View is for presenting data and human actions for manipulating it, Controller is for translation between user actions and the various views, and the Model is where business data and the business reasons for it to exist reside.

Michael K
  • 15,539
  • 9
  • 61
  • 93
2

The point of OOP is to group together data and functionality that belong together. A calculation that is based on some piece of data does not always belong with that data.

In MVC the functionality to display a piece of data (view) is kept separate from the data (model). Why is that? It's specifically so that the display logic can be changed without having to change the underlying data. It makes it easy to change the view whenever you need to make a different presentation of the same data: or when the characteristics of the display hardware change: or when you switch from Windows to Linux; or when you want two people to have two different ways of looking at the same data.

MVC isn't in conflict with OOP - it is actually derived from a correct application of Object Oriented Principles.

DJClayworth
  • 538
  • 4
  • 9
0

As I understand it; The argument is component based architecture vs OOP. And without getting into the religious war, I think that they are both describing the same thing; just looking at it from different angles.

For example, the whole point of OOP/OOD is to make your code more modular and reusable. Yes?

Which is exactly the goal of component based architecture. So they are more alike than anything else.

I think that MVC is just the natural evolution of OOP and dare I say it; a better way to organize your objects, separation of concerns and code reuse.

gnat
  • 21,442
  • 29
  • 112
  • 288
djm
  • 109
  • 3
  • I'd say the MVC and Component-Based Architecture are design patterns not outside of the realm of OOP approaches while OOD/OOP is simply a bunch of confusion and clashing of schools of thought and malacademia on how to use a bordering-on ubiquitous programming construct properly. Comparing the two categories of things is like comparing squares and the pen you used to draw the squares. – Erik Reppen Oct 11 '12 at 00:49
0

I believe you're confusing persistent data bound to a model object with the application data from the databases the model interacts with. A model contains business logic and rules for working with databases and conducting transactions. It might set and check internal state flags like whether there's a sale today, whether the user qualifies for VIP status and then branch logic accordingly when it comes time to access, set, or manipulate data or conduct a purchase. It's those flags we're talking about when we discuss objects in terms of encapsulation of a set of methods and persistent values or data.

Just as the model object maintains data for establishing what business rules are in play, a controller should, IMO, hold on to more general application state data pertinent to how the app should behave, like whether the user is logged in or they have valid credit card data in place. Model methods would determine the state of these things in the first place but it makes sense for the controller to maintain flags pertinent to general app flow if they don't apply to how the business is run or data transactions are conducted. Once you've determined they're not logged in, don't even bother the model with user state checks until it's clear another log-in attempt is being made.

Likewise with a proper view object vs. the more typical HTML templates you see in most server-side web frameworks. Once the user's color preferences are loaded up, it should be the view that holds on to that data and executes on it. Loading, validating and changing settings are all model problems but they should only be model problems once until changes happen.

IMO, nothing says controllers can't be composite objects with views and models as internal aggregate objects. This actually makes sense if you apply MVC on a smaller scale like a UI widget factory since the controller is the ideal place to expose an interface to higher level app objects while burying the data and logic details of how the View and Model interact. It doesn't really make sense for monolothic app objects where the controller is really the highest level object though.

Erik Reppen
  • 6,243
  • 31
  • 34
-1

I am late to this party, and considering all the answers before mine, I admit I don't have much new to offer. But it seems to me that the question isn't about the pattern itself but about the implementation. MVC in and of itself does not lend itself to any particular methodology. In fact, I can easily envision procedure oriented code in an MVC pattern (which is what I felt like you were implying).

So, I think the real question is; are we more prone to procedural code when using the MVC pattern.

(and maybe I'll just get some down votes?)

aserwin
  • 161
  • 6
-1

Not anti, but also OOP is not required for MVC.

Because controllers, which are usually represented by classess hold no data. For which pure functions would suffice.

If you go further and separate data from behaviour, for example let's say that models work only on database data, which they fetch every time their function (that is responsible for data manipulation) is called (instead for storing some kind of data in the instance fields) - then you can say the same for the models.

Going further, if you take the view layer of an application and divide it in similar fashion, you will actually end with conclusion that MVC has nothing to do with OOP, and it is completely possible to write MVC implementation without any pain using only procedurall approach.

luke1985
  • 219
  • 2
  • 8
  • Haha, I see some people got pain in the a** when faced with facts. Too much effort doing own frameworks with OOP? Can't stand the lost time? The simplest answers are the best. – luke1985 Mar 18 '14 at 20:39
  • Not sure why this answer has downvotes. He's saying they are not related, and not "anti". Seems pretty accurate. – mwilcox Apr 02 '15 at 16:36
-3

In my Opinion OOPs has a drawback that since the (data and behavior) are moulded as one entity(Class) this shows more coupling effect than cohesion. Whereas on the other hand MVC it has Model containing...(Beans, DAOs, Other Logic classes), Controller that specifies how the control must travel and Views to determine how the data should be shown are given in a seperated fashion. Based on this no matter if the project is Too big to prepare can be easily made as seperate entity other than getting mixed unlike OOPs. The problem is solved in logical pattern just like divide n conquer strategy and MVC follows this atmost.