Yet Another MVVM question... Is my understanding correct? - mvvm

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.

Related

Data ownership and reference in MVVM (specifically C++/WinRT, UWP, WinUI)

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. :)

Does knockout.js really employ MVVM pattern?

I am new to knockout.js. Few moments back I read the headline features of ko.
I could not understand is ko really MVVVM? Because all they talk about is data binding and the ease of it. But I am sure MVVM is more than data binding isn't it?
Yes, knockout.js does apply the MVVM pattern. It's explained in the documentation:
A model: your application’s stored data. This data represents objects and operations in your business domain (e.g., bank accounts that can perform money transfers) and is independent of any UI. When using KO, you will usually make Ajax calls to some server-side code to read and write this stored model data.
A view model: a pure-code representation of the data and operations on a UI. For example, if you’re implementing a list editor, your view model would be an object holding a list of items, and exposing methods to add and remove items.
Note that this is not the UI itself: it doesn’t have any concept of buttons or display styles. It’s not the persisted data model either - it holds the unsaved data the user is working with. When using KO, your view models are pure JavaScript objects that hold no knowledge of HTML. Keeping the view model abstract in this way lets it stay simple, so you can manage more sophisticated behaviors without getting lost.
A view: a visible, interactive UI representing the state of the view model. It displays information from the view model, sends commands to the view model (e.g., when the user clicks buttons), and updates whenever the state of the view model changes.
When using KO, your view is simply your HTML document with declarative bindings to link it to the view model. Alternatively, you can use templates that generate HTML using data from your view model.
In addition to the answer already provided, there are a few things to keep in mind -
MVVM
Knockout is MVVM because it supports a good separation of concerns. Unlike other JavaScript libraries, such as jQuery, it's goal is to not pollute the view with that which does not concern it.
The view model's purpose is important to understand. It does not attempt to manipulate the DOM because only logic required to serve up data to the view is placed inside of it.
The view's purpose is only to present (render) the data. No logic, validation, or other logic code goes here.
The model is the only place where Knockout can get a bit tricky. It is generally a good accepted practice to place a separate model in your project for Knockout to use, but many developers have found the ease of mixing the model into the view model. The reason for this is obvious (some models are very basic) but again this is only out of ease of implementation.
MVC vs MV*
Surely there are other answers on SO.com that attempt to answer what is MV*, but I wanted to throw my $0.02 in here - Other libraries or frameworks speak to the fact that they are MVC or MVP or MV(whatever) based but Knockout is the only one that I have found that practices what it preaches in this regard. If you have the time and desire look at the structure of other frameworks such as Angular or Ember and you will see there is a blurred line that exists, and more or less they are simply using an MVVM based pattern but calling it something different.
Well I guess it can, however I am working on a project where all styling and UI layout manipulation is done in the knockout js ViewModel file, which is not good practice.

MVVM using constructors of UI to pass model

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).

Entity Framework, MVVM, and Calculations Classes

I'm working on a database application that manages industry-specific inputs and then runs that information through somewhat complicated calculations, lookups, etc. to return a series of other values and a go/no-go conclusion.
I've decided to use Entity Framework (code first for provider independence) and WPF (MVVM pattern). I'm using the POCO entities as my data model and the view model is handling the usuals like basic data / business rule validation.
It seems EF + WPF/MVVM are great at displaying and validating input and getting it into the database for querying for your typical business application like a products, customers, orders setup. But it's not at all clear where to plug in a "calculations layer". Between the view models and the data models (my POCOs), things are already feeling a bit bloated, and now I'm facing adding another layer very much like the other two.
Perhaps the best way to approach this is to make the calculations layer a sort of meta-view model and push as much of the validations, change notification, etc. into them and run with lighter actual view models.
Anyone run into a situation like this?
Edit
Turns out what I really needed was to thin the view models and beef up the entities. So I lightened the view models, moved property change notification and basic validation to entities to allow for direct binding, and made calculation classes directly consume entities as well as adding some basic routines to entities. Thanks for the links on thought ADM articles #Peter Porfy.
For moving validation closer to entities, used Fluent Validation (excellent suggestion #Gloopy!). To make it easier to implement property changed notification on entities, adapted this technique. And to avoid having to create endless property wrappers in view model (to set HasChanges property) I used Josh Smith's PropertyObserver.
MVVM stands for Model-View-ViewModel, where the Model layer contains everything what models your actual domain problem.
So it depends on what you mean 'calculation layer'.
Put it where it belongs.
If the actual operation belongs to a domain entity, then you should put that logic into the entity. Don't make anemic domain models:
Article from Martin Fowler about ADM.
DDD works perfectly with EF code-first.
If something doesn't belong to any entity then probably you should expose that as a service. Then use that from your viewmodels through an interface.
A dependency injection container could make your life easier here, but you can live without it.
You aren't plugging another layer because it's the model layer. Your viewmodels should stay as thin as possible, just modelling your view's state and forwarding actual business operations to the entity/service classes.
I'd probably create an interface/object to handle calculations (or several if they can be split up logically) and pass that object in wherever you would want to use it. You might benefit from using a dependency injection framework maybe this post can help with that so you wouldn't have to explicitly instantiate your objects where you need them.
Also this post mentions FluentValidation.NET which may not apply completely but there are likely some good patterns to learn from/use there as well.

Why have ObservableCollection and INotifyPropertyChanged in Model?

I've read on msdn that it is common for Models in MVVM to implement interfaces such as ObservableCollection<T>, INotifyPropertyChanged, and IDataError.
My question is around why this is done at the model level and not the ViewModel level. I would expect that a "pure" Model would not have any notification logic, just data and business logic. My first impression is that the VM would wrap the Model's properties and take care of the notifications.
I readily admit that implementing these interfaces in the Model may make implementation easier in many cases, but I'm looking for an explanation as to why the model should be responsible for notifications.
INPC is part of the Core framework unlike say ICommand and DependencyObject which belong to WPF specifically. There was a similar question regarding exposing IQueryable from the service layer. Just like INPC, IQueryable is a core framework class. Not using either of them in an effort to create a pure model is overkill.
Even worse it causes duplication (making the VM wrap expose properties just to add a propertychanged notification).
Observable Collection on the other hand is a different beast. Usually collections in a domain model represent entity relations. In many cases, you don't have control over their instantiation. There's a tradeoff to be made there
Depending on your application, you might have multiple Views and ViewModels of the same data. Say you have one window that shows a list of items with read-only details, but in another window you have the ability to add, edit, and remove items.
If the Model uses ObservableCollection and INotifyPropertyChanged, the changes made in the editable View/ViewModel will be seen and updated in the non-editable View/ViewModel.
Furthermore, if the non-editable View is simple enough, it can be possible and acceptable to simply expose and bind directly to the model. As there is no ViewModel to handle the notification, the Model would need to do the job itself.