How Open Close Principle decides which instance of interface to use? - clean-architecture

I am reading the clean architecture chapter - 8 Page number 72, The Open-Closed Principle.
The chapter has a thought experiment of a system that displays the Financial data on a web page and there is a requirement to show the data on black-white printed page with proper page headers, page footers etc.
Uncle bob says that the problem should be modeled as shown in the diagram. In the diagram controller has no dependency on the Screen Presenter or Web Presenter and it's easy to add another Presenter as well.
Does this architecture means that for formatting the data in the pdf format. I will have to initialize a new instance of the Financial Report Controller with Print Presenter as one of the instance variable?

I will have to initialize a new instance of the Financial Report Controller with Print Presenter as one of the instance variable?
No. But you will have to pass the appropriate Print Presenter to the Financial Report Controller somehow.
When you decide which one is appropriate doesn’t have to be on initialization. You could pass it later with a setter. Or you could pass a collection of them to choose from.
Or, like you said, create a new instance of the controller. They all work. Use what makes sense for your situation.

Related

Understand architecture of MVC application

There are many articles available to explain architecture design of MVC application , some contains business layers , domain layers and etc.
I would like to know each & every terms and what should be inside that layer?
Presentation.Web : MVC application goes here Business.Domain :
?? Infrastructure.Data : ??
What are others layers should be there to and what is use of that to create ideal architecture of MVC application?
This nice article by Russell East could help you out - http://russelleast.wordpress.com/2009/04/04/aspnet-mvc-defining-an-application-architecture/
I will try and explain it in a technology neutral format:
mvc is short for model , view, controller.
===========================================
Model isn't the girl/boy walking down the stairway showing off trendy clothes.
But its an object that contains valuable properties (data)
For instance:
In RPG (role playing game) every character has stats such as
health , magic, attack, defense, evasion, accuracy, etc.
Those stats are called properties in classes.
Character acts as a class that contains all those properties.
===========================================
Now, talking about the View,
View is something that displays about a particular model.
For example:
We have a health bar that display total health and current health.
Some might be interested to see a heart shape to represent health
instead of a red bar.
The developer starts creating another different view but still uses the same model . It's talking about reusability!
You are reusing the same model to display its properties in many ways!
============================================
For the controller, its the place where your business logic is defined.
Business logic (or also known as the 'fun' part of coding)
is a place where you define some code to manipulate the properties in
model and send them to the view.
For example:
So let's assumed that the hero has full health,
An enemy attack him...
The controller (who has access to the model) manipulates your
Character health by deducting current health by total damage received
from enemy attack.
When your character drinks a health potion,
the controller increments your character current health.
==========================================
For the communication part,
the controller who manipulates the model,
can inform the view about the changes made,
so that the view will display the most recent changes to your character.
Or
the model dispatches event whenever a property has been changed,
and the view who is currently subscribing to a model ,
will then take necessary actions to update the view by using the current
manipulated property.
You can also have a look at this link
The following might explain:
MVC Architecture
The main aim of the MVC architecture is to separate the business logic and application data from the presentation data to the user.
Here are the reasons why we should use the MVC design pattern.
They are resuable : When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
They are expressive: By using the MVC design pattern our application becomes more expressive.
1). Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.
2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view's to maintain the consistency in its presentation when the model changes.
3). Controller: Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. In GUIs, the views and the controllers often work very closely together.
Source: http://www.roseindia.net/struts/mvc-architecture.shtml

MVC: Are Models and Entity objects separate concepts?

I asked here a while ago for some help in understanding MVC, since I'm very new to the topic. I thought I had a decent understanding of it, and this is documented in a blog post I wrote recently on the subject. My understanding basically boils down to this:
Controller: Determines what needs to be done to fulfill a request, and utilizes whatever models it needs to collect/modify as needed. It's basically a manager for a given process.
Views: Presentation only. Once a controller collects what it needs, it creates a specific type of view, hands it the information, and says "show this to the user however you do it."
Models: Behavior of the application. When the controller asks it to extract or modify something, it knows how to do it. It also knows to trigger other models to do related tasks (in my understanding, when a model tries to "vote for something" on StackOverflow, that model knows to ask if a badge should also be granted because of it. The controller doesn't need to care about that).
My question, assuming all of that is more or less accurate, is where do entity objects come in? Are models and entities the same thing, with each object knowing how to persist its own data, or are entities a separate concept that exist on their own and are used throughout the application?
My money is on the latter, since this would allow models to act independently, while all three layers (model, view and controller) could utilize the entities to pass data around as needed. Also, objects and database persistence seem like concerns that should be separated.
To be honest, the more I read about MVC the more confused I get. I'm about ready to just take the core concept (separate presentation from logic) and run with it in whatever way feels right, and not worry too much about the "MVC" label.
Yes!
My money is on the latter, since this would allow models to act independently
You don't want to bind your view to an Entity, because if the view also needs some other piece of data, you would have to it to your Entity. The model is entirely supportive of the view, and is concerned with supporting that view and nothing else.
For example, you show a list of your entities, what other data might you need? Current page number? Total number of pages? A custom message to be displayed?
This is why you should bind to a model, which you can freely add data items to as you need to.
Update
Here is an explanation of MVC in action...
The controller gets all of the data required for the request and puts it into the model. It then passes the model to the view.
The view then deals with the layout of the data in the model.
Each Model can be one entity that contains some methods to control and use its data.
Is it enough?

Getting started with software design using MVC, OO, and Design patterns [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 6 years ago.
Improve this question
NOTE:
This question has been updated to provide more detail and insight than the previously.
UPDATE:
I just want to say thank you to everyone who responded. I'm still pretty much in the dark on what design pattern would work best for the Widget. Perhaps one of the Factory or Builder patterns?
I am just getting started on a new project and need to use MVC, OO and design patterns.
Here's the idea: Imagine a page that displays a set of widgets. These widgets are (usually) charts that are based off of data contained in several separate tables in the database. I use a running example of page that reports on a student's performance.
High Level Requirements
a page that displays a set of (HTML only) widgets.
widget's data will be based off a database query.
the page can be used to view separate datasets containing similarly laid out data. For example, a single page will display widgets that report on various aspects of a single student's performance.
want to see another student's performance, pull up another page. Displaying different widgets for different students is not needed (though it may be nice to have later).
There may be many students, but data contained in the database is similarly laid out for all students.
the way a widget is displayed may be changed easily (say changing a widget from displaying as a pie chart to display as a bar chart).
widgets should be able to be created quickly.
Low Level Requirements
Currently data does not change so widgets will not need to automatically update themselves.
Widgets may represent a ratio of two things (eg. a ratio of failed tests to successful tests as a pie chart), a series of points, or sometimes a single numeric value.
Development of new widgets should be a breeze, existing code need not be modified.
Framework to be used: Zend Framework, based on MVC.
There are (minimally) three things to define a widget: the dataset to report on (in the example above, the student ID), the query that describes the metric being reported, and a render mode (barchart, timeseries etc).
Here is a pass at breaking down the responsibilities of each layer of the MVC:
View: Zend views are HTML templates with PHP injected. They will contain one of several types of widgets. Widgets are of various forms including: static JPEG images (loaded from a remote site ie: <img src="http://widgetssite.com?x=2&y=3"/>, JSON based javascript widgets, or charts of various kinds (piechart, bar chart etc.)
Controller: Creates the widgets, assigns them to the view afterwards. The set of widgets that is to be displayed on a page needs to be maintained somewhere. Since I can't think of a good way to do this in the view, I'll add this to the controllers responsibilities for now. If there's a better place for this please shout. The controller will also have to handle any other input parameters and passing them to the widget. For example, the data_set id which may be passed at the url line as http:/.../report/?student_id=42
Model: The model, in the Zend Framework, is responsible for pulling the data and as such will most likely contain a class for each widget for accessing the database.
Some points:
The model here, represents the data for a particular widget. So necessarily, it will need to know what the query is going to be, in order to pull together the tables necessary to fetch that data.
There's an additional processing step that will most likely be necessary before the widget can present the data. This is dependant upon which renderer will be used. Sometimes it may require forming a url out of the data returned. Other times, a JSON array. Other times perhaps creating some markup. This can go either in the model or the controller or the view. Unless anyone can think of a good reason to move it to the controller or view, it is probably best to let this live in the model and keep the view and controller thin.
Likewise, a widget will be made up of 3 things, its parameters, its data, and its renderer.
One big part of the question is: What's a good way to represent the widget in an Object Oriented design? I already asked this once, couldn't get an answer. Is there a design pattern that can be applied to the Widgets that makes the most sense for this project?
Here's a first pass at a rather simple class for the Widget:
class Widget{
//method called by the view
render() {//output the markup based on the widget Type and interleaved the processed data}
//methods called by the controller:
public function __construct() {//recieve arguments for widget type (query and renderer), call create()}
public function create() {//tell the widget to build the query, execute it, and filter the data}
public function process_data() {//transform into JSON, an html entity etc}
//methods called by the model:
public function build_query() {...};
public function execute_query() {...};
public function filter_data() {...};
}
Looking at it, I can already see some problems.
For example, it is straightforward to pass the widget that was created in the controller to the View to render.
But when it comes to implementing the model it seems not so straight forward. Table Gateway Pattern is simpler to implement than ORM. But since table gateway pattern has one class for each model/table it doesn't seem to fit the bill. I could create a model for a particular table, and then within that, instantiate any other models needed. But that doesn't seem so to fit the Table Gateway Pattern, but rather ORM pattern. Can Table Gateway Pattern be implemented with multiple tables? What alternatives are there? Does it make sense that the controller creates the widget and the widget creates the Model?
Another issue that arises is that this design does not enable ease of widget creation. ie. Say I wanted to create a PiechartWidget, how much code can be reused? Would it not make more sense to use some OO ideas such as an interface or abstract classes/methods and inheritance?
Let's say I abstract the Widget class so only the shared methods are defined concretely, and the rest are declared as abstract methods. Revising the Widget class to make it abstract (second pass):
abstract class Widget{
private $_type;
private $_renderer;
//methods called by the controller:
//receive arguments for widget type (query and renderer),
protected function __construct($type, $renderer) {
$this->_type = $type;
$this->_render = $renderer;
$this->create();
}
//tell the widget to build the query, execute it, and filter the data
private function create() {
$this->build_query();
$this->execute_query();
$this->filter_data();
}
//methods called by the model:
abstract protected function build_query();
protected function execute_query() {
//common method
}
abstract protected function filter_data();
//method called by controller to tranform data for view
//transform into JSON, an html entity etc
abstract protected function process_data();
//method called by the view
//output the markup based on the widget Type and interleave the processed data
abstract protected function render();
}
Is this a good design? How could it be improved?
I assume writing a new widget will require at least some new code to build the query, and maybe filter the data, but it should be able to use preexisting code for almost all of the rest of its functionality, including the renderers that already exist.
I am hoping anyone could provide at least some feedback on this design. Validate it?
Tear it apart. Call me an idiot. That's fine too. I could use any forward traction.
A few specific questions:
Q1. What's the best way to implement the renderers, as part of the Widget class or as a separate class? 1a. If separate, how would it interact with the widget class(es)?
Q2. How could I improve this design to simplify creation of new kinds of widgets?
Q3. And lastly, I feel like I am missing something here with regards to data encapsulation. How does data encapsulation relate to the requirements and play out in this scenario?
For #2, if you are using WPF on windows, or Silverlight in general, consider using MVVM pattern (Model-View-ViewModel), here is explanation with a WPF implementation:
MVVM at msdn
For #1 (comments not answer): For exact implementations (and minor variations) of MVC, it really depends on what language you are using.
Another alternative to MVC is MVP Model View Presenter
Remember the goal of OO is not to cram design patterns into your code, but to create maintainable code with less bugs/increased readability.
High Requirements
- a page that displays a set of widgets. widgets are based off of data contained in several separate tables in the database.
- widget's data will be based off a database query. widget display its data in a particular way.
- widgets should be able to be created quickly.
Low Level Requirements
- Data changes, multiple charts need to change, push model (from data to ui)
- Development of new widgets should be a breeze, existing code need not be modified
Advice from design patterns basics
- MVC supports one to many notification pattern, so yes, once your widget is initialized, created and connected to the web page, it should wait for notifications from the database.
- Strategy pattern, your entire code should develop to a interface. New widgets should be added to a parametrized LinkedList (or some other data structure). That way new widget developers just implement the interface and your framework picks up these notifications without change to existing code.
Siddharth
The purpose behind all of these ideas -- MVC, patterns, etc. -- is essentially the same: every class should do one thing, and every distinct responsibility in your application should be separated into distinct layers. Your views (page and widgets) should be thin and make few if any decisions other than to present data gathered from the models. The models should operate on a data layer agnostically, which is to say they should not know whether the source of their data is a specific kind of data source. The controllers should be thin as well, acting basically as a routing layer between the views and models. Controllers take input from the users and perform the relevant actions on the models. The application of this concept varies depending on your target environment -- web, rich client, etc.
The architecture of the model alone is no trivial problem. You have many patterns to choose from and many frameworks, and choosing the right one -- pattern or framework -- will depend entirely on the particulars of your domain, which we have far too few of here to give you more specific advice. Suffice it to say it is recommended you spend some time getting to know a few Object-Relational Mapping frameworks for your particular technology stack (be it Java, .NET, etc.) and the respective patterns they were built on.
Also make yourself familiar with the difference between MVP and MVC -- Martin Fowler's work is essential here.
As for design patterns, the application of most of the standard GOF patterns could easily come into play in some form or another, and it is recommended you spend time in Design Patterns or one of the many introductory texts on the subject. No one here can give specific answers as to how MVC applies to your domain -- that can only be answered by experienced engineers in cooperation with a Product Owner who has the authority to make workflow and UI decisions that will greatly affect such decisions in their particulars.
In short, the very nature of your question suggests you are in need of an experienced OOP architect or senior developer who has done this before. Alternatively give yourself a good deal of time in intensive study before moving forward. The scope of your project encompasses a vast amount of learning that many coders take years to fully grasp. This is not to say your project is doomed -- in fact you may be able to accomplish quite a lot if you choose the right technology stack, framework, etc., and assuming you are reasonably bright and focused on the task at hand. But getting concepts as broad as "MVC" or "OO" right is not something I think can be done on a first try and under time constraints.
EDIT: I just caught your edit re: Zend. Having a framework in place is good, that takes care of a lot of architectural decisions. I'm not familiar with Zend, but I would stick to its defaults. Much more depends here on your ultimate UI delivery -- are you in a RIA environment like Flash or Silverlight, or are you in a strict HTML/JavaScript environment? In either case the controllers should still be thin and operate as routers taking user requests from HTTP gets and posts, and immediately handing off to the models. The views should remain thin as well and make as few decisions as possible. The concept of MVC applied in a web environment has been pretty well established by Rails and the frameworks that followed, and I'm assuming Zend is similar to something like CakePHP in this regard: the application server has a routing system that maps HTTP calls to controller actions that respond with specific views. The request/response cycle is basically this:
User request posted through a URL
Router hands control to a controller class
Controller makes a call to a model with the given params
The model operates on the data, posts back to the controller
The framework maps the finished data into a view, with some kind of code-behind that puts the results of the request in the view's scope.
The framework creates html (or xml or whatever) and posts back to the caller.
It sounds like you want to use MVC and other patterns because they are the new buzz words. Splitting your design among model view and controller should tell you how to spread the functionality of your application. Although I totally agree that using MVC is the correct approach, I suggest you research the pattern and look at some source code that implements it. As a start to your question though, the widgets that will be displayed will be your views, that much should be obvious. Input from the user, such as changing a parameter of some widget or requesting other information will come into your application and should be handled by a controller. A concrete example of this is a Java-based HttpServlet. The controller servlet receives the user request and asks the lower layers of your app (Service, Persistence, etc) for an updated representation of your model. The model includes all of your domain-specific objects (i.e the data from your databases, etc). This data (the updated model) comes back to the controller, which in turn pushes out a new view for the user. Hopefully that is enough to get you started about designing your app.
As further help, you could consider using a framework to assist in the development of your app. I like Spring a lot, and it has a first class MVC implementation that really helps guide you to designing a correct MVC web app.
You may consider using Subject Observer Pattern
Have your class, named DataReader as single Subject. Your multiple widgets will act as Observers. Once your DataReader receives data from server, it (Subject) will inform multiple widgets (Observer).
Your individual widgets may have different presentation to present to same set of data from DataReader.
Update
In the message where subject notify observer, you may include the message type information as well. Widgets will only process message type, which is within their own interest, and ignore rest of the message.
NOTE: This is my new answer based on new the updated question.
Here is a proposed class diagram. I'm going to work on a sequence diagram.
My old answer is here:
Based on the requirements you describe, your model is your database or data warehouse and your views are your pie charts, bar graphs, etc. I don't see the need for a controller, because it sounds like you have a one page dashboard with widgets.
You need to spend your time on the database model. Since you're doing all selects and no updates, go for a de-normalized data model that makes these queries efficient. You should put the results of these queries in a table type object (e.g. 2-dimensional array) or 3-dimensional array based on the amount of dimensions. You are limited to 3 dimensions unless you use animation.

MVC - Who formats the model?

Before rendering into a view model should be formatted:
multilingual data localized;
date, time values formatted;
numbers formatted.
Who performs all this formatting - Controller or View?
Am I right that all the formatting is performed by the Controller which creates so called ViewModel containing only formatted values and sends this ViewModel to the View?
Thanks in advance!
Eric Petroelje is right, but I would build helper a class(es) to get localised content/dates etc, because localisation isn't always in the views, e.g. sending emails with localised content. I would have something like LocalisationHelper.GetString("MyKey"), or LocalisationHelper.GetDate(Date.Now), where the LocalisationHelper knows the users current locale (maybe from Session).
Then use this directly in the views where possible:
<%= Html.Encode(LocalisationHelper.GetDate(Date.Now)) %>
Design Patterns 101.
Model is for storing data (usually database-backed).
View is for presenting the data (not manipulating it).
Controller is for manipulating the model and passing that to the view (choosing the right locale for instance would go here).
MVC doesn't necessarily mean you have 3 distinct classes, but rather 3 components or layers. These are abstract and don't necessarily have to be tied to one physical class. Inside your Controller layer, that can consist of any number of helper classes or whatever.
I agree with part of what cartoonfox is saying, everything is intertwined. For instance, if you develop a view for a shopping cart, but the model is containing birthday information, then it isn't going to work. It is simply a design pattern to help remove duplication of effort. When you have fewer variables and less noise, it is much easier to focus on what needs to be done and understand it very well.
I had a discussion with our team about using annotations to render forms on a web page. These annotations were placed in the model or entity class. You will often work directly with entity classes, so it eliminates quite a bit of overhead and duplication of effort if you put your annotations here. Because your annotations are placed directly on the model class, you cannot end up with a view for birthday information, it just isn't possible. In addition, by following patterns, you strip out the junk that doesn't add value to the end result. You simply write the business logic and close to nothing else.
Although the annotations were in the same class as the model layer, the presentation or view layer consisted of the annotations and the helper classes. It doesn't need to necessarily be distinct classes or boundaries.
Another example would be. I've worked on some PHP web "applications" in the past. I use applications because they were a monolithic block of code, more or less a single main method with all the logic in there (which is hardly a functional application).
If you don't abstract code into functions and simply use a single method, you will end up with a lot of duplication of effort. If you tried to understand that monolithic code block, you would be in for a heap of trouble (as was I, it was hard to learn what was going on, then I would find a similar block of code somewhere else and be dumbfounded why a few things were tweaked the way they were).
It can be done any way you want, but design patterns such as MVC help you simplify what you write in order to get it to work as well as more easily wrap your head around the solution. Another popular design pattern or approach is divide and conquer.
To answer your original questions:
In Java, localized data would be done transparently by the application. For instance, if you wanted US English locale support, you would create a properties file:
messages_en-US.properties
and then place all your US English content in there. Depending on how much content this may be, you might want to use a different approach.
For my application I have whole pages in a different language so what I do is this. My controller determines the client's locale or a best match. Then it chooses which view to display and passes the model (data) to the view.
If you need dynamic formatting for your date/times, then your controller is responsible for determining which one will be used. Then, your view is responsible for using that converter to format the value.
I'm using JBoss Seam so the MVC design pattern is still used, but more abstractly. I don't have actual 'controllers', but an interceptor which is responsible for handling a specific piece of functionality (determining the client's locale, then another for their date/time preference). My controllers that would be the equivalent of a Spring Controller are action components responsible for handling page actions.
Walter
The view is responsible for this not the controller.
To explain I need to elaborate a bit about what the "view" is:
In both web-based and traditional GUI MVC patterns, the View is responsible for the external representation of whatever parts of the model that are shown. If that means "formatting" data from the model then so be it.
The controller shouldn't format the data - because the controller is responsible for doing things to the model based on events/commands coming in from the outside world. The controller doesn't have anything to do with rendering the output.
Example:
I want to display a shopping cart with several order lines:
Adding things to the cart causes the controller to change what's in the cart model.
Changing my locale causes the controller to change a setting in the user model to indicate preferred locale.
Whenever the cart is displayed, the view has to ask the model for the order lines and decide how to display that - maybe doing locale-sensitive work.
The same customer could ask to see the shopping cart in multiple different currencies. That just means changing what it looks like in the view. It's still the same shopping cart for the same customer with the same things in it.
If this is a web-app made from web template pages, you might embed code to pull in localized messages e.g. <%= message_renderer.text(:insufficient_funds) %>. In this case the "message_renderer" and the template file are both part of the view.
Views aren't necessarily just web-based templates. In some Java-based frameworks for example, we put "view objects" into a velocity template. Those view objects are linked back to objects in the model, but they also perform on-demand rendering and formatting behaviour. Those are part of the view although they're not just a template.
It's a bit confusing with frameworks like ruby on rails and groovy on grails where they call the template the "view" - when a view is really more than just a template. Traditionally (in Smalltalk MVC and in Java's Swing) views are just code that can perform formatting, rendering and any other display-related behaviour.
All that stuff seems like presentation layer logic, so personally I think it should go in the view.
ETA:
I wouldn't advocate for having the view call service layer objects in the general sense, but for localization I think it makes sense.
For example, lets say you have lots of static text on your pages that you have tokenized and stored in a database in various localized forms. I don't think it would make sense for the controller to have to lookup and put all those text tokens in the model. Even though a text token lookup is technically a "service layer" operation, I still think it makes sense for the view to call that service directly via some utility class rather than having the controller do it.

Can any processing be done on the model? [MVC]

I've decided to make a big push towards MVC for all new sites I make. I have a question about whether or not you can have any processing on the model level.
The case that brought up this question is a video site. I have a Video class (model) and one of the things I need to do when a user views the video I need the view to be logged in the database. I'm not sure if I need to add a query in the controller or if I can add a addView method in the Video class.
The basic underlying question for me is what kind of methods am I limited to in the models? Can it be anything or does it have to be only accessor (a.k.a getValue/setValue) methods?
Ruby on Rails has the motto skinny controller, fat model. This doesn't apply to just Rails and should be practiced with any mvc framework.
I think your model is exactly the place to handle this. Now, your model is necessarily composed of just your entity classes. Your model, in my opinion, would include your entities as well as any business logic that you need to implement. Your controller should just be handling I/O for the view, invoking model methods to accomplish the actions invoked by the user via the user interface (view).
Here how I would do this. It should be valid in pretty much any language.
The View would initiate a method call to the controller's OnView() method, then display whatever the controller spits back to it (in a controlled way, of course... I'm thinking your view is going to contain a video player component, so you're going to get a video of some kind back from the controller)
In your controller, have a method OnView() that does 3 things: instantiate the Video object (i.e. uses your data layer to get a model object), call the updateViewCount() method on the Video object, and display the video (by returning the Video object to the View, presumably).
The Video model object contains data representing your video and any houskeeping stuff you need, which includes updateViewCount(). The justification for this is that a Video has a view count (aggregation). If "view count" needs to be a complex object instead of just an integer, so be it. Your data layer that creates Video objects from their primitive representation on disk (database?) will also be responsible for loading and creating the corresponding view count object as part of the creation of the Video.
So, that's my $0.02. You can see that I've created a 4th thing (the first three being Model, View, and Controller) that is the data layer. I don't like Model objects loading and saving themselves because then they have to know about your database. I don't like Controllers doing the loading and saving directly because it will result in duplicated code across Controllers. Thus, a separate data layer that should only be directly accessed by Controllers.
As a final note, here's how I look at views: everything the user does, and everything the user sees, should go through the view. If there's a button on the screen that says "play", it shouldn't directly call a controller method (in many languages, there's no danger of doing this, but some, such as PHP, could potentially allow this). Now, the view's "play" method would just turn around and call the appropriate method on the controller (which in the example is OnView), and do nothing else, but that layer is conceptually important even though it's functionally irrelevant. Likewise, in most situations I'd expect your view to play a video stream, so the data returned by the controller to the view would be a stream in the format the view wants, which might not necessarily be your exact Model object (and adding that extra layer of decoupling may be advisable even if you can use the Video object directly). This means that I might actually make my OnView method take a parameter indicating what video format I want to get back, or perhaps create separate view methods on the controller for each format, etc.
Long winded enough for ya? :D I anticipate a few flames from the Ruby developers, who seem to have a slightly different (though not incompatible) idea of MVC.
Since you can use whatever model code you want with MVC (not just limited to LINQ) the short answer is yes. What should be done in the model is perhaps a better question. To my taste, I would add a ViewCount property (which probably maps to a column in the Video table, unless you are tracking per user in which case it would be in the UserVideo table). Then from the controller you can increment the value of this property.
With MVC, people seem to be struggling with fitting four layers into three.
The MVC paradigm does not properly address the data storage. And that's the "fourth layer". The Model has the the processing; but since it also addresses the data, programmers put SQL in there, too. Wrong. Make a data abstraction layer which is the only place that should talk to back-end storage. MVC should be DMVC.
Keep in mind, there are many variations on MVC and no real "right way" to do things. Ultimately, how you design your classes comes down to personal preference. However, since you asked for design advice, here are my two cents:
Business logic belongs in the controller. Keep it out of the model and view.
Out of the many variations on the MVC pattern, the passive view style seems to be the easiest to test. In the passive view, your classes are designed as follows:
Your controller is "smart: it makes changes to the database, updates the model, and syncronizes the view with the model. Apart from a reference to the model and view, the controller should hold as little stateful information as possible.
The model is "stupid", meaning it only holds the state of the view and no additional business logic. Models should not hold a reference to either the view or controller.
The view is "stupid", meaning it only copies information from the model to the UI, and it invokes event handlers which are handled by the controller. The view should contain no additional business logic. Views should not hold a reference to the controller or model.
If you're an MVC purist, then it would not make sense for the model to update itself or the database since those responsibilities belong to the controller, so it would not be appropriate to create an addView method to your Video class.

Resources