MVC: Where should I put this data access logic? - model-view-controller

I've been trying to adhere to a strict interpretation of MVC in rebuilding a personal web application at home, but I'm having some issues.
The application is a financial tracking application. I'm stuck at the first page, which is just a list of the bank account transactions for the month. The transaction list is my Model. The Controller and View are easy enough to envision at this point.
However, I also have two buttons at the top of the page. They are arrows, one corresponding to the previous month, and the other corresponding to the next month's transaction list. I don't want these buttons enabled if there are no transactions for the previous/next month, so I need to talk to the database to figure out whether each button should actually link somewhere.
From most of what I've read, to the largest extent possible database access should be encapsulated in models, with little to no database access in Controllers and Views.
However, these buttons essentially need to ask the database, "Are there any transactions for the next/previous months?" The answer will determine whether or not their links are disabled, as well as where to send the user.
Strictly speaking, putting their logic into the Transaction List model does not seem appropriate, as whether or not transactions exist outside the requested range is beyond the concern of the Transaction List Model.
I guess I could also make another Model that would correspond to all Year-Month combinations where transactions exist. I could then pass this Model and the Transaction List on to the proper View.
Or should I deviate from the no-database-access-outside-the-model paradigm, and just throw some quick DB querying into the View (since the result is essentially a UI concern, making navigation easier)?
What do you guys think about this conceptual issue?
BTW, I am not using any framework. This is pet project designed to get me more familiar with the nuts and bolts of the MVC pattern.

... should I deviate from the no-database-access-outside-the-model paradigm, and just throw some quick DB querying into the View ...
The short answer is: no. If you're truly interested in learning MVC and better coding in general, taking shortcuts "just because" is a very bad idea. Domain logic separation is a fundamental concept of MVC, and to violate it would essentially be moving out of MVC into territory that is dominated by terrible code and "MVC Frameworks." If you want to learn "the nuts and bolts of MVC," you'll have to understand that the nuts and bolts are things like separation of concerns, and they are very important.
A lot of the text in your question suggest a few mixed ideas about what a model should be, so I'm going to redirect you to the most linked-to answer regarding MVC models. That answer encompasses everything you'll want to know about the concept of models. To summarize the most important concept from it, a model is not a class, it's a layer. The model layer has many components that all do their own thing, which leaves you with a testable, extensible, semantic, and logical domain logic layer.
Just remember to be careful: There is way more mis-information out there about MVC than there is reliable information. The worst thing you can do to learn proper MVC is look inside of a framework that claims to be MVC.
edit: I assumed the language was PHP while responding, so some of my answer might reflect that assumption. However the concepts are applicable across nearly all languages

The application is a financial tracking application. I'm stuck at the first page, which is just a list of the bank account transactions for the month. The transaction list is my Model. The Controller and View are easy enough to envision at this point.
Everything on your web page, is categorised in the View domain. A "list" is a visual object.
For a web application/page, The model exists on your server, within your database. Everything that exists on the web page, (Buttons, Forms, List boxes etc) is you View domain.
From most of what I've read, to the largest extent possible database access should be encapsulated in models, with little to no database access in Controllers and Views.
The View objects traditionally talk directly to your Model objects. Which means you have to provide a way for your View objects to talk to your database.
An example,
http//server/transactions (Get all transactions)
http//server/transactions?from=x (Get transactions from x)
http//server/transactions?from=x&to=y (Get transactions from x to y)
Could be your interface to your Model by your View.

Related

Cocoa MVC ≠ actual MVC?

Today I was getting some refresh about software design patterns.
In particular I was wondering about the difference between MVC and Three-tier-layer. Basically, from what I read on wikipedia and other sources, the main difference between the two is the components interaction:
A fundamental rule in a three tier architecture is the client tier
never communicates directly with the data tier;
whilst
...the MVC architecture is triangular: the view sends updates to
the controller, the controller updates the model, and the view gets
updated directly from the model
Now: if we take the apple docs regarding this matter we see this:
And they clearify that Views and Model shouldn't communicate directly:
view objects are typically decoupled from model objects in an MVC
application
and
When a model object changes (for example, new data is received over a
network connection), it notifies a controller object, which updates
the appropriate view objects
And so on.
So, what's the matter here? Is Cocoa adopting its own idea of an MVC, regardless of the common one? Or am I missing something in the common way of seeing an MVC architecture?
While it can be said that Cocoa's version of MVC is a sort of subset of the actual definition of MVC, they are not separate entities. The Cocoa version of MVC typically revolves around the use of a View (typically an NSWindow and/or an NSView), a controller (typically an NSWindowController), and a model layer (anything from a simple array to a Core Data stack). The separation of powers in this model is clear, but where in the 'tier' structure that Wiki defines should each of these belong?
I would argue that the Controller and the View are a part of the client layer. Not only is the controller responsible for the delegation between the model and the view, but it is responsible for responding to user events and determining the correct course of action to take during non-framework error handling. By taking this approach to MVC, you can now begin to see how Cocoa does, in fact, satisfy the broader definition of the pattern.
A fundamental rule in a three tier architecture is the client tier never communicates directly with the data tier;
This one's probably the hardest to reason about of the 3, and it involves delving into what "communication" actually means in the context of the pattern. When we say communication, what we mean is that the controller has no direct involvement in the actions taken by the model. That's not to say that the controller cannot order a change in the contents of the model, but rather that the controller does not have a hand in how the model updates itself. The controller acts as a director, not an implementer, which vastly simplifies the creation of a database layer, and is one of the reasons that Core Data and SQLite3 exist as external frameworks rather than as Foundation classes.
view objects are typically decoupled from model objects in an MVC application
That brings up one of the age-old taboos when programming with the pattern: making your views too smart. The controller provides a solid barrier between the model and view, such that the controller acts as a director and a filter for content from the model layer. Without any such barrer, say a tableview, would have to ensure that every cell had a copy of the data from the database, and that each cell knew when and how to update itself when a change is propagated in another cell. In Cocoa, this is where our NSWindowControllers come in. They manage the display of a root view and act as a barrier between some model and the content of the view it manages. Though, it is important to note that the controller objects in Cocoa are view-biased, mostly because it would be nearly impossible to provide a generic outlet to any kind of model layer without quite a bit of unnecessary glue.
When a model object changes (for example, new data is received over a network connection), it notifies a controller object, which updates the appropriate view objects.
That's the way it should be, for the reasons I've laid out above. But, to build on the networking example you've given, consider this:
Given an NSOperation that fetches data, and a controller that manages a tableview, you would probably not like the controller sticking its fat fingers into the operation, nor would you like the tableview to receive raw NSData and have to spend valuable rendering time processing the result and displaying it.
And so on. So, what's the matter here? Is Cocoa adopting its own idea of an MVC, regardless of the common one? Or am I missing something in the common way of seeing an MVC architecture?
I guess the conclusion I would draw from this is that your definition of the separation of powers in MVC and in how Cocoa does it is off. Cocoa is fairly rigid about adhering to the pattern, though there is an interesting contemporary movement within the Objective-C community towards MVVM.
You are correct the MVC practiced in most cocoa apps is not the MVC as it is defined in the text books. There are many variations of MVC employed by different frameworks. The MVC employed by tools with visual designers are heavily influenced by their visual designer implementation. With XCode you have story boards and nibs. The cocoa libraries and the way concerns are separated are influenced by this. If you want to take advantage of these tools, I would recommend understanding how concerns are separated by Xcode and work within this approach. Your code will coexist with it more smoothly. Apple documentation will help with this.
That being said, MVC is about separation of concerns. Separating concerns is hugely important in designing and maintaining software. Separating concerns properly can reduce dependency, reduce cyclomatic complexity, and make your code much more testable and maintainable. I think it is good that you are paying attention to this and whatever way you structure MVC should look to the reason why you are separating concerns as the guide to implementation.

Does Domain Driven Design require to implement the business logic outside the domain objects.

The model of the domain are my entities used as POCOs which means no base class, no interfaces around and no Attributes.
So the business logic like validation rules must be outside of the entities. (Anemic Domain Model)
Would this comply with Domain Driven Design?
No. Not really.
Main aim of domain driven design is to capture and encapsulate business domain in model explicitly as possible. Business would always contain behavior, therefore - Your objects are supposed to have behavior too.
The model of the domain are my entities used as POCOs which means no base class, no interfaces around and no Attributes.
...and no c#, .net clr should be used. that's infrastructure, right? ;)
Those are tools to express Your model. You should try to keep noise level down, separate Your model, but You won't be able to runaway completely because it's a model of real life expressed in programming language and technology around it.
Btw, You might want to investigate idea of never allowing domain object to be in invalid state. And if it feels that this particular kind of validation does not relate to business - it is not supposed to be in domain model first of all.
That's a really philosophical question. I really want to give an equally philosophical answer, so here goes:
As I have understood domain driven design, the most important thing is that whoever knows something, does things with that knowledge. I believe this to be intertwined with this article.
With this in mind, your plain old objects should have the means of performing their "life or death" - important tasks (which makes your solution wrong).
However, another way of looking at it would be that these plain old objects are the tiniest available sets of data, almost like primitives. What happens then is that the objects owning these data objects, they are the actual model objects within the domain driven design. and they don't have to correlate perfectly (which would make your solution correct).
This could easily happen if the model and the data layer are designed by two completely independent designers, or if one person is capable of switching hats. Or maybe be a little.... wohoooooo D: i'm thinking this could be a good thing though! let me give an example:
A forum
What do we need? We need users, boards, threads, and posts. The last 3 all have a "one to many" relationship in the data layer. One board has many threads, and one thread has many posts. One user also has many posts, and one user starts many threads (could be derived by finding the author of the first post in a thread, so might not have to be stored in the data layer). But what is going on in the presentation layer?
When viewing a board, we will want to see all available threads in that board. but we won't be satisfied with seeing the name of the thread, and the name of the user who started it. We also want to see the number of posts in each thread, plus the name of the last poster in the thread, and the time of that posting.
We are now looking at a model object which is somewhat out of sync with the data layer. It will contain business logic to calculate the needed data from the given data objects, and then it will be able to load some sort of view with the data that the view wants. No getters or setters will be needed in the model, so capsulation is never broken. The model object conforms to the domain, which should be dependant on the usability demands, not the limitations of data storage. The data objects conform to the old data storing style.
This would give us a data abstraction layer (with the pocos), mvc, and domain driven design. win? :)

What should my ASP.NET MVC Controllers represent - "real world" application

I have an established web application built as an ASP.NET 3.5 Web App. We recently modified it to mix MVC into the app for some new functionality.
Now that it's in there, we want to leverage MVC wherever possible to begin to "transform" the app from clunky webforms to a more maintainable and testable MVC app.
The question that just came up in adding some new functionality is what controller should be responsible for a certain action.
Let me be more detailed.
The scenario involves at least three major conceptual areas in our app. The app needs to be able to set their PREFERENCE for a default MAP view while they are on a SEARCH screen. Preferences, Maps and Search are all major concepts in our system. Furthermore, this preference setting (basically, where should the map start out) may be used to set the initial map in more than one search page (it's basically a search preference).
The existing MVC controller in the app is a MAPCONTROLLER, with 3 actions that are responsible for generating HTML or JSON data to put on a map.
What we need to do now, is add an MVC route (controller + action) to allow the client view to save some information as their preference. Basically, whenever they are on the search page looking at a map, they can click a button that says "remember this as my default map view", and from then on, their map will always start with that view.
My question is (and I apologize, but I wanted to be very very clear, I see too many questions with no context to help). What should my controller represent? I obviously have 3 major system areas involved. Would it be proper to create a new SEARCH or PREFERENCES controller with a SaveDefaultMapView action (no view required), or piggyback on the xisting MAP controller, even though this new function is more about search and preferences than actual map generation? Should an MVC controller be aligned mostly with the screen (search page/search subsystem), the domain / data being manipulated (preferences), or the very specific visual element under scrutiny at the time the action is taken (the map)?
All of the examples and bootcamp projects are all well and good, but they are far too clean and simplified to apply to a huge legacy app. How does one design their MVC components around a system that incorporates many domain concerns into a single webpage?
Thanks all!
There are no hard and fast rules for how the controllers are organized. You organize them the way it makes most logical sense to you. This will require a bit of experimentation as you see how the routing works out, and you find the cleanest, most elegant design.
ASP.NET MVC is brilliantly agnostic in this respect. It doesn't care how you design your controller/route substructure, and it is flexible enough to handle most any design.
Your application design should be heavy on the Model side. Your controllers should be relatively small; if you find that you are stuffing a large amount of logic in the controllers, you should refactor that logic to the model, or add a service layer to contain the logic. Your controller layer is best thought of as a "patch panel"; it is the place where you connect your incoming Urls via routes to your model/service layer and your View Model/Views.
You should definitely check out Project Areas, as this might be an appropriate mechanism to contain your three different system areas.
Thanks, Robert.
I guess I could rephrase a bit...what guidelines have others found to be useful for keeping their controller responsibilities organized and logical?
While my example above only touches 3 of our areas, I expect to eventually replace most/all of the application with MVC.
Furthermore, each of the 3 areas I mentioned has relationships to multiple other areas.(eg, maps can be used to plot several location-based entities, preferences can apply to any area of the system, and, like maps, is capable of searching for several kinds of business entities (one at a time, not all together).
So the lines are blurry. I'm interested in hearing how others have found workable guidelines for controller organization.
Oh, and at the very least, we are sticking to the skinny controller/fat model paradigm!

Model View Presenter (MVP) What is the model?

I just cannot seem to get my head around what exactly is the MODEL in MVP.
If I have a layered architecture PRESENTATION / APPLICATION / DOMAIN / INFRASTRUCTURE, what exactly is the MODEL?
DOMAIN objects accessed through
lower layers?
A separate object defined in the
PRESENTATION layer that maps to the
UI and uses data obtained from a
lower layer?
If someone could clear my understanding on what is the MODEL it would be greatly appreciated.
The Model is normally the group of classes/types/components that represent the core domain (business or otherwise) that your application operates within. These are the classes that perform the key logic required, often in the form of business rules, and also consume/manipulate data.
In your layered example, the Model would mostly be found in the Domain layer but could also be in the Application layer.
I think you're having difficulty understanding it because you are trying to combine two separate architectural patterns, or ways of looking at the application, being n-tier/n-layer versus MVP.
It's completely reasonable (and quite common) to use some sort of Model/View approach while at the same time applying layering in your application.
Maybe you should focus on them one at a time to start with and then overlay them when you are more familiar with both.
In any of the Model-View-* architectures, the Model is what describes the data in your application (and, if they fit the need, are passed in to the View for rendering).
If your application already has Domain objects, it very well may be the case that you could use them for your Model.
It doesn't matter what architectural guidelines you're following, M is always going to be the same thing. The Model is the piece that is specific to your domain. It's the part that really is what you're application is trying to do. The Model is supposed to represent your business domain. This goes for MVP, MVC, MVVM, etc.
If you were making a inventory system, then an Inventory class would most likely be in your Model, a Product would probably be there, an Order, you get the idea. These are the things that compose your domain logic.
The model is the data. This might just be data out of a database in DataSets, or it might be a complete domain model with objects representing your field of business.
The view is the UI, whether web pages or a Windows application or a mobile device application.
The presenter is the glue between the two and the brains of the whole outfit. Actions initiated by the view take place in the presenter. Generally in a WinForms application, for instance, a Button.Click event in my View simply calls a method on the Presenter, which then takes whatever action is necessary (and it may just be doing something back in the View).
The presenter holds a reference to the view (through an interface), and to the model. The view has a reference to the presenter (usually I strongly-type this, but it can be an interface as well). The model doesn't know about the presenter or the view.

What is MVC and what are the advantages of it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I found What are mvp and mvc and what is the difference but it didn't really answer this question.
I've recently started using MVC because it's part of the framework that myself and my work-partner are going to use. We chose it because it looked easy and separated process from display, are there advantages besides this that we don't know about and could be missing out on?
Pros
Display and Processing are seperated
Cons
None so far
MVC is the separation of model, view and controller — nothing more, nothing less. It's simply a paradigm; an ideal that you should have in the back of your mind when designing classes. Avoid mixing code from the three categories into one class.
For example, while a table grid view should obviously present data once shown, it should not have code on where to retrieve the data from, or what its native structure (the model) is like. Likewise, while it may have a function to sum up a column, the actual summing is supposed to happen in the controller.
A 'save file' dialog (view) ultimately passes the path, once picked by the user, on to the controller, which then asks the model for the data, and does the actual saving.
This separation of responsibilities allows flexibility down the road. For example, because the view doesn't care about the underlying model, supporting multiple file formats is easier: just add a model subclass for each.
Separation of concerns is the biggy.
Being able to tease these components apart makes the code easier to re-use and independently test. If you don't actually know what MVC is, be careful about trying to understand people's opinions as there is still some contention about what the "Model" is (whether it is the business objects/DataSets/DataTables or if it represents the underlying service layer).
I've seen all sorts of implementations that call themselves MVC but aren't exactly and as the comments in Jeff's article show MVC is a contentious point that I don't think developers will ever fully agree upon.
A good round up of all of the different MVC types is available here.
Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).
I think another benefit of using the MVC pattern is that it opens up the doors to other approaches to the design, such as MVP/Presenter first and the many other MV* patterns.
Without this fundamental segregation of the design "components" the adoption of these techniques would be much more difficult.
I think it helps to make your code even more interface-based.. Not only within the individual project, but you can almost start to develop common "views" which mean you can template lot more of the "grunt" code used in your applications. For example, a very abstract "data view" which simply takes a bunch of data and throws it to a common grid layout.
Edit:
If I remember correctly, this is a pretty good podcast on MV* patterns (listened to it a while ago!)
MVC is just a general design pattern that, in the context of lean web app development, makes it easy for the developer to keep the HTML markup in an app’s presentation layer (the view) separate from the methods that receive and handle client requests (the controllers) and the data representations that are returned within the view (the models). It’s all about separation of concerns, that is, keeping code that serves one functional purpose (e.g. handling client requests) sequestered from code that serves an entirely different functional purpose (e.g. representing data).
It’s the same principle for why anybody who’s spent more than 5 min trying to build a website can appreciate the need to keep your HTML markup, JavaScript, and CSS in separate files: If you just dump all of your code into a single file, you end up with spaghetti that’s virtually un-editable later on.
Since you asked for possible "cons": I’m no authority on software architecture design, but based on my experience developing in MVC, I think it’s also important to point out that following a strict, no-frills MVC design pattern is most useful for 1) lightweight web apps, or 2) as the UI layer of a larger enterprise app. I’m surprised this specification isn’t talked about more, because MVC contains no explicit definitions for your business logic, domain models, or really anything in the data access layer of your app. When I started developing in ASP.NET MVC (i.e. before I knew other software architectures even existed), I would end up with very bloated controllers or even view models chock full of business logic that, had I been working on enterprise applications, would have made it difficult for other devs who were unfamiliar with my code to modify (i.e. more spaghetti).
One con I can think of is if you need really fast access to your data in your view (for example, game animation data like bone positions.) It is very inefficient to keep a layer of separation in this case.
Otherwise, for most other applications which are more data driven than graphics driven, it seems like a logical way to drive a UI.
If you follow the stackoverflow podcasts you can hear Jeff (and Geoff?) discuss its greatness. https://blog.stackoverflow.com/2008/08/podcast-17/. But remember that using these separate layers means things are easier in the future--and harder now. And layers can make things slower. And you may not need them. But don't let that stop you from learning what it is--when building big, robust, long-lived systems, it's invaluable.
It separates Model and View controlled by a Controller,
As far as Model is concerned, Your Models has to follow OO architecture, future enhancements and other maintenance of the code base should be very easy and the code base should be reusable.
Same model can have any no.of views e.g) same info can be shown in as different graphical views.
Same view can have different no.of models e.g) different detailed can be shown as a single graph say as a bar graph.
This is what is re-usability of both View and Model.
Enhancements in views and other support of new technologies for building the view can be implemented easily.
Guy who is working on view dose not need to know about the underlying Model code base and its architecture, vise versa for the model.
One of the major advantages of MVC which has not mentioned here is that MVC provides RESTful urls which enables SEO. When you name your Controllers and Actions wisely, it makes it easier for search engines to find your site if they only take a look at your site Urls. For example you have a car sale website and a page which displays available Lamborghini Veneno cars, instead of having www.MyCarSale.com/product/6548 referring to the page you can choose www.MyCarSale.com/SportCar/Lamborghini-Veneno url for SEO purpose.
Here is a good answer to MVC Advantages and here is an article How to create a SEO friendly Url.
Main advantage of MVC architecture is differentiating the layers of a project in Model,View and Controller for the Re-usability of code, easy to maintain code and maintenance. The best thing is the developer feels good to add some code in between the project maintenance.
Here you can see the some more points on Main Advantages of MVC Architecture.
![mvc architecture][1]
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.

Resources