I heard a bit about we should keep the code in controllers as less as possible. So where do we put those code?
This will depend on what code you are talking about. For example if you are talking about validation, this should go into the model, if you are talking about data access this should also go into a repository or the model (personally I prefer repository), if you are talking about a business logic this should go into a service, so that all that's left into the controller is to call this thing and pass the result to the view.
I would recommend you watching this video presentation about how to put your controllers on a diet from Jimmy Bogard.
Do you know thin and skinny controller? So my answer is if you put many line of codes in controller, your code will be messy and hard to unit testing. Really the controller only executing the actions related with current HttpContext, so if you have business logic, data access, encryption,... you must separation of concern. The reason you don't put business logic at here is business belong to domain. So delegate to Domain for processing. Controller must be consider all actions related to HttpContext (Session, ViewData, TempData, User in current thread, Global and Local Resources,... ) and delegated all other actions to other component. Rule of thumb is fat model and thin controller for cook delicious cake(phpcake).
Some links you can reference for skinny and fat Controller at here and here.
Related
I've set up a very simple (Universal Windows) App in C++/WinRT.
It's just App <- MainPage <- DataViewModel <- Data for now.
MainPage has some Sliders etc. which are bound (x:Bind) to DataViewModel, which contains an instance of Data. Working fine so far.
However, the Data is a member of DataViewModel. This seems to be an obvious code smell. Data should not be "owned" by the GUI. All Examples/Samples I've come across seem to be set up like this, though.
I also want to run a background thread (pure C++ code) that works with one and the same instance of Data.
The question: Who "owns" Data. How do I connect things? How to pass the reference?
My best idea so far: The App class itself should just own the one instance of Data. The MainPage ctor should take a Data& and pass it on to the ctor of DataViewModel. However, I don't seem to be able to write a custom ctor for MainPage, because there's generated code involved.
Just pointing me to well coded Sample App would also be appreciated.
IInspectable (in the comment above) makes a noteworthy point: "Ownership really only matters when non-static lifetimes are involved. If Data represents data with static lifetime then there's nothing inherently wrong with exposing it through a static App class member."
In this vein, don't limit your thinking of Data (i.e., the model) to just object(s) which some other object owns. The model should be thought of as a wholly independent component.
Let me approach this notion from another angle. Most people will readily describe MVVM as three independent "layers" or "components" or what have you, wherein the model "doesn't care" about the view model, which in turn "doesn't care" about the view.** In code (as you have seen yourself), you're probably going to find some clear cut ownership patterns to reflect that basic premise. For example, if we're following the the "view-first" approach like the Microsoft samples, you'll start with your App object, which owns an instance of a view object, which in turn instantiates a view model instance.
But the key to MVVM is not who owns whom, it's the relationships between those layers. If you wanted to, you could write a program where, say, the views and view models were all static members of the App class and still have a (conceptually) textbook MVVM structure once everything is hooked up. From that perspective, it doesn't matter where ownership resides.
Now, the thing about Microsoft samples like the Photo Editor is that ultimately they're just demonstrations of how things can work, not a treatise on design patterns. Consider when your data is coming from a database or a web service. Where do you draw the conceptual line between model and view model? The question may sound pedantic, but the way you evaluate these things influences your design decisions.
Which brings me back to your specific question. If it seems like code smell to you when examples you find online stick the model data any old place, you're not wrong. In "real life," the model can be an entire API, not just one illustrative class. You'll potentially have an elaborate subsystem delivering data to you that depends on services completely separate from your application. Or it might be an opaque third-party API that you're calling into via global functions, etc. Just remember that the key isn't "ownership," it's (the conceptual) "relationship." ***
** As a side note, you mention Data being a member of DataViewModel and describe this as Data being "'owned' by the GUI." Ideally, the view model should have no inherent ties to the UI, just application logic. Don't think of it as an extension of UI functionality.
*** But please don't take this post to imply that the actual implementation of the MVVM paradigm isn't important. That's true of any design pattern. The exact form that implementation takes depends on the specific application and whatever your boss wants you to do. All I'm saying is, don't get hung up on ownership. :)
I'm over-thinking this and getting myself into a muddle but can't clear my head.
I'm new at WPF and I'm trying to get familiar with MVVM. I understand the theory. I need a view, a model and another model (called the view-model).
However, what happens if my model is constructed by a parameter of the View's constructor.
So, assuming I have a totally empty project, the only thing is I've an overloaded MainWindow constructor which takes the model:
public MainWindow(Logging.Logger logFile)
{
InitializeComponent();
this.DataContext = logFile;
}
The Model is the logFile. Can I still implement the MVVM when I don't have a separate Model class?
Any thoughts would be appreciated.
You're overthinking this.
There are several components to MVVM:
View:
The view provides a, well, view on the data. The view gets its data from a viewmodel
ViewModel:
The viewmodel is there to organise your data so that you can organise one or more sources of data into a coherent structure that can be viewed. The viewmodel may also perform basic validation. The ViewModel has no understanding of the UI so should not contain references to controls, Visibility, etc. A viewmodel gets its data from services.
Services:
Services provide data from external sources. These can be WCF, web services, MQ, etc (you get the idea). The data the service returns may need to be shaped so that it can be displayed in the UI. To do this you would take the raw data from the service and convert it to one or more Model objects.
Model:
A model object is an object that has been created so that it can be easily displayed/work with the UI.
You may find that you don't need to shape your data coming from your services (lucky you), in which case there's no need to create model objects. You may also decided that you don't want your services talking directly to your viewmodels but instead what to have them get their data via a "mediator" object. That's also good in some situations (usually when you're receiving a continuous stream of data from a source/multiple sources).
MVVM is a bit like porridge: there are lots of potential garnishes you can add, but you don't necessarily need to add them all. Or want to.
Does this help?
Edit: just stumbled on this: a more in-depth expression of what MVVM is:Mvvm Standardisation. This may also be useful
The Model is something the ViewModel will know about but not the View. If you need to present info about a Logger, you can certainly have a LoggerViewModel that knows about a Logger, and in turn the View winds up getting to know about the ViewModel. There are several ways to do that, and setting the DC in the view constructor is one of them.
After that basic understanding of who knows about who, what really makes the MVVM architecture pattern, IMO, is that ViewModel communicates to the View via databinding. Nothing more and nothing less. Lots of goodies come out of this, but that is the crux of it that makes it different than other separation of concerns patterns (like Presentation Model, MVP, etc)
That said, you need to get a feel for it by working through some sample projects. Asking questions here on SO is fantastic when you get stuck on something, but you must realize your question here is a bit fuzzy at best. Also, unless you are really looking to present logging info in your view, logging is not an MVVM concern. Its interesting alright but not MVVM.
Google Josh Smith's MVVM demo on MSDN for a perfectly meaty yet approachable beginning sort of project. And ask more questions or refine the one here as they come up!
HTH,
Berryl
forget the view! at least at the beginning ;)
try to think about what you want and what you need. what i understand is that you wanna handle a logfile. so you need a viewmodel for that.
public class LoggerViewmodel{}
you can put the logfile as a parameter to the vm ctor. now you have to think about what you wanna do with your logfile? for everything you want create a property (LastModified, LastRow, whatever) on your viewmodel.
btw there a two different ways to do mvvm, first is view first and the other is viewmodel first. i do both in my projects and take the appraoch wich fits better (viewmodel first the most time ;)) to my needs.
pls edit your questions and add what you wanna do with your logfile, then we can give you a better answer.
edit:
Can I still implement the MVVM when I don't have a separate Model class?
to answer your question the short way - yes you can. you have to seperate the view and viewmodel and use binding to bind the view to the datacontext(viewmodel).
I have read a lot of gwt-mvp questions that are asked here, but since i'm totally new to this design pattern I would like to ask some questions:
[1] The Activity-Place pattern is a different pattern than mvp?
[2] In the MVP pattern presenters contain the logic. Now the logic of the widgets/controls is defined in the Activities?
[3] The CustomPlace classes are fixed (as the Eclipse plugin constructs them) or can i put data/methods and what kind?
[4] What is the use of the Presenter interface inside a CustomView? What data/methods would make sense to add into it?
[5] I want to build an application that will use many data structures that will be saved into a database. I have read some other posts here and I will make the Model part of MVP live inside each Activity. So i think to create each time the data structures of each activity at start and load its values (if necessary from db) and will update the database after the user goes to another view. What do you think about this approach?
Let's start by debunking one myth: Activities/Places have nothing to do with MVP. Places is about navigation, Activities are about "componentizing" the UI wrt Places. On the other hand, MVP is a design pattern, it's about how to organize your code.
Many people are using their activities as their MVP-presenters, but it's not enforced. The GWT team is trying a new approach where the activity is distinct from the presenter (work underway in the mobilewebapp sample if you want to follow what's going on there). You could also have your activity being your view and making use of an "internal" presenter (similar to how Cell widgets work)
A Place is more or less a URL. You can put whatever you want in it. I'd suggest making places immutable though: build a Place, goTo it, make use of its properties to build your UI.
That's about MVP then. This is only needed to decouple your view and presenter, mostly to make mocking in unit tests easier (this is particularly of the view interface though, not much for the presenter one, unless writing a test harness for you views). In some cases, you might also want to use the same view with distinct presenters; they'll all implement the same interface so the view can talk back to them.
How about the closing of the window/tab? I'd rather use a periodic auto-save, or an explicit save button; and implement mayStop so it prompts the user when there are unsaved changes (similar to how most desktop office apps work —e.g. MS Word or LibreOffice—, and GMail if you try to navigate away before your mail draft is auto-saved)
The Activity-Place is an implementation of the pattern. Google introduced gwt-mvp pattern at Google IO, but only provided it's implementation as part of GWT about a year later.
Yes Activities contain business logic. No, widgets/controls usually do not contain any logic, they just fire events based on user action. The logic that acts upon those events is written by user and resides elsewhere.
I don't use Eclipse, so wouldn't know about Places generated by it. Normally custom Places can contain custom fields and methods. For example they can contain custom place token arguments, i.e. if place token is "#place:id1", than your custom Place could contain field holding this argument.
When View needs to call/access Activity, it does so via Presenter, which Activity implements. For example when user enters all data in a for and presses submit, then you could have a method in Presenter named submit(formData).
Preparing/loading data in activity.start(..) is a normal way of doing things. If particular activity is used a lot, then you might consider caching the data if appropriate.
It seems to me that as I'm working with View and Controllers, that Controllers only handle the first level of their respective folder.
/Controllers/MembersController
/Views/Members/
How is the Controller supposed to handle sub-folders?
/Views/Members/Business
The Controller isn't. If you want a page at the url /Views/Members/Business/ThePage, you'll solve that with a route definition in your global.asax.cs. If you need to put views in subfolders for organization, you should consider splitting up your controllers.
Update in response to your comment.
In short: yes, the routing definitions are responsible for choosing what controller should handle your request.
It seems that a slightly more detailed walkthrough of how the MVC framework was designed to be used might be in place. I'll keep this really basic, and skip all the stuff about the framework's internal workings. (That will make some advanced readers think I'm saying stuff that's flat out wrong. Please bear with me - I'm just being intentionally sloppy...) Here goes...
When a request is submitted from a browser to your web server, the MVC framework goes to the route definitions to see where the request should be sent. It looks through them in the order you define them, top first, so if there are several matches only the first one will be relevant. (Therefore, you want to keep your very general routes, like the default one, at the bottom.)
When the framework has decided that a route is a match, it looks up what controller and action the url should be routed to. It fills in all action parameters with data from the url, and calls the action method.
The action method on the controller is now responsible for being "the spider in the center of the web", that instruments everything that needs to be done to serve the response. This might include querying your model for data, calling various library methods for calculations or almost anything else. The final step of the controller method is determining what response should be returned - in most basic cases, the response should be a view, and the code for returning it is return View();.
The view (or whatever other result you're returning) possibly gets some data from the controller, and is then responsible for rendering this data correctly. When the view has done its job, the framework serves it back to the client.
As you can see, the decision on what controller action should be called is much earlier (step 1 and 2) than the decision on what the return result should be (end of step 3), and the two of them aren't even necessarily related to each other.
To reflect this in your application, you want to have a folder and file structure for controllers and views that corresponds to the available controllers and their action methods (at least those of them that can return a ViewResult), and a route collection that reflects what urls you want your user to use to get to these controller actions. By defining more routes than the default one, you can get quite a variety of url structures, without changing your controller/action method/view structure at all.
If all of this still seems like a labyrinth of decisions, it might be appropriate to go to http://www.asp.net/mvc/ and watch some of the learning videos or read some tutorials. There are some really good both videos and texts there about how the framework works, and how it's intended to be used.
In your controller action, you can return a view from any folder you want like this:
return View("/Views/Members/Business/Index.aspx", model);
If anyone is still interested in a solution, MVC has a thing called "Areas" that allow you to define subfolders.
http://msdn.microsoft.com/en-us/library/ee461420%28v=VS.100%29.aspx
Sorry if this is a duplicate, It's not so much 'What is MVVM' though, but rather, 'Is this MVVM', I've read quite a bit, and think I've got a basic understanding of what it is, I've got my own 'one-liner', as such, on how I interpret it, but want to make sure it's correct before I firmly ingrain it in my head,
Essentially; The Model is pure data - no methods, there is one ViewModel per Model, it holds a reference to the Model - it performs all changes to the Models data and finally the View will hold one (or more) ViewModel reference(s) and format & display the data provided by the ViewModel.
(Not after links to tutorials, blogs etc, just a yes, or no with tweaks will be fine, as I'll have to re-read everything again anyway if not :) )
Not completely - at least, not as I would completely define it.
The Model does not have to be pure data. The model is the portion of your application that is completely domain specific, and has no "presentation related" information.
This will typically include all of the domain specific data, but also potentially methods that are pure business logic, and data access, etc. Anything specific to the business logic and processes, and not part of the "display", is part of the model.
Also, although "one ViewModel per Model" is the most common form of working, there are times when you may expose a "model" class through multiple ViewModels. This can be useful, for example, if you are trying to expose only part of a model to your designer, as it allows you to make a smaller ViewModel class. The ViewModel adapts the model for work with the View - if the entire Model is not required, this adapter can be made smaller (and more easily testable, maintainable, etc) by only working with the portion required.
Personally, I prefer to think in terms of "one ViewModel per View", as the ViewModel can adapt one or more models in order to work appropriately with a given View, but even then, sometimes it's helpful to swap out a ViewModel within the same View in order to change content.
Close, but not quite. Here are some points that are are different than yours:
Models can have methods on them. They are not just data. They might have methods like "retrieve", "store", etc. Business logic code. View agnostic.
There is no restriction to how many ViewModels hold a reference to the Model. ViewModels encapsulate view-level behavior, so you may have many different sets of behavior for the same model. For example, one ViewModel might be a read-only transformation of a model item. Another might provide read/write form validation on the same model item.
There can be more than one ViewModel per view, based on the behavior you want. For example, you might include "premium content" behavior with one ViewModel and "free content" behavior with another ViewModel but maintain the same view.
Essentially, yes. Practically, not really. Best practice is always to reduce dependencies and split up your responsibilities among classes on a 1:1 basis, but you'll find IRL situations where it isn't as easy to be a MVC purist.
I think the best attitude is to do your best, then document the rest. Don't sweat purity too much.
There is a lot of great information here, and I think that most of these answers are right. I don't think there is any 1 specific definition, nor is there 1 specific authority on this matter. Even microsoft does not really have clear definition on this.
The one item I would add which is not in the name of MVVM, but is common to all implementations of MVVM that I am familiar with. This is a Messaging or Notification system, which seems to always be linked as a platform for the ViewModel. Messaging just notifies the View Models when things change which may affect others. A good implementation of this in mind allows View Models and Views to both be agnostic about things they do not directly bind to by using generic notification messages.
The benefit of the entire pattern in my opinion is to make you application with modular, swappable parts with as little type-dependency as possible.
This is a real missing part in my mind, as it provides the same benefits / functions that you gain from separate controller logic in the MVC pattern.
That is pretty close. Except it is not correct to say that the Model is only pure data. It can and should contain methods for performing the various use cases against it.
Your understanding is wrong.
You can have several Models and all of them could have their own Views and then be a part of a single ViewModel.
Example:
You have the Models: Product, Customer
Each of them have their own View represented as a Custom Control
And you have a ViewModel which combines all your models and finally on the window of your app you combine all together your Views which talk to your Models via your ViewModel
Think of it like this. The Model is your system, the meat and veg of what the system does. The only considerations it has is how to do it's job, not how it is going to be used. It exposes events, attributes and methods defined at the system level, but it has no concept of what will be pressing it's buttons (or if it even has buttons!). It does not try to format data to a more user friendly format, it formats its data in a model friendly way.
The view model is the UX (user experience). It defines how you are going to use the system. It defines (through public commands and attributes) user orientated access into the system. It is the bridge that the user will use to enter the system. It binds onto the events of the model, and through it's commands, it will provide access into the models functionality.
It should handle validation, (is that age a sensible age?) retrieve data, converting and caching of records whilst they are being displayed. So, for example, you're looking at a patient record, the viewmodel gets the data from the model, and caches it internally, then publishes this to the view. What happens if the model announces an update to that data? Throw the cached data away? what if you've edited it? This is all up to you, and this behavior should be defined in the view model.
The view model is a "contract" of what functionality and data is exposed to the user (through the view). The view model has no concept of HOW it is going to be displayed or interacted with. Commands should be named at a functional level, such as RefreshList, NOT MouseClickHandler.
Finally, the View. This is simply a visible representation of what is in the view model. Buttons and menus etc bind onto commands. Fields bind onto attributes and will update automatically through the magic of binding.
If you ever see yourself doing : "text1.text = value" you're doing it wrong. If you ever find yourself writing a command handler that says "my.ViewModel.SomeCommand" you're doing it wrong.