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

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

Related

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

View and Servlets in website class-diagram?

I'm about to develop this small website, its basically a simple web app to store informations about patients for a doctor.
The company i have got the assignment from demands an introducton with a class diagram, honstly, i have done this already but only for standalone apps, i'm very new in designing class diagrams for websites.
What i'm using is the Ivar Jacobson's iterative metho with usecases, where a usecase includes:
Actors, scenario (representing user-system interactions when all goes fine), and worse case scenatio (solutions when something goes wrong).
By applying this i came to a good conclusion, a well prepared class diagram.
My problem is that i'm doubting whether or not i should include jsp views and servlets(in my case action beans since i use Stripes) in the diagram, i mean, the bridge between the business-classes and the user are the jsp-views and the provided info are going to be processed by the servlets (or action beans), would you include them in the class diagram?
For a small project tis might be not that relevant but what if you have a project with 30 views and 20 servlets, the diagram would become messy and huge.
Do you have some tips about it?
Thank you
If the only reason you need the class diagram is to satisfy the client, best find out what they're looking for first.
If however they're not specific (and ignoring the cynical options) I'd suggest the following:
Create a "Domain Model" diagram. i.e. capture the concepts in the domain and their inter-relationships. So Doctor, Patients and associated stuff.
Don't create a "design" class diagram - i.e. no jsps, servlets, etc. If necessary create a simple architecture picture instead showing how the application is layered.
Rationale: a domain model is good for checking scope and verifying domain rules (relationships). A "design" class diagram only obfuscates that. A proliferation of jsps, controllers, etc. hides the underlying architecture pattern while distracting from the useful stuff in the domain model.
hth.

How can I use the new GWT MVP framework?

I need a tutorial for the new GWT MVP framework which is presented here.
The description Google gives is a little bit short for me. What are the meanings of — and how do I use — the following?
Activities
Places
Eventbus
ClientFactory
PlaceHistoryMapper
ActivityMapper
Also, where are the models in this new framework?
Places
These are classes that encode information about where your program has navigated. You might make a Place that means, "I'm on the home screen," and another one that means "I'm editing the user with id 52384. I think a better name for these would be PlaceTags, because they are not actually a place themselves - they just indicate where your program is. The URL is hooked to Places in a PlaceHistoryMapper, in which you can say, "hey, #home should generate a HomeScreenPlace and #edituser:52384 should generate a EditUserPlace (maybe constructed with a field you set to 52384).
Activities
These start and stop your code. Each Activity has a start method that is called when appropriate. You determine what "when appropriate" means by making an ActivityMapper, which has a function called getActivity. getActivity accepts a Place, and you have to decide which Activity to return. If the Place is whatever you've coded to mean "I'm on the home screen," you might return a HomeScreenActivity, and if the Place means "I'm editing the client with id 523584," you might return a EditClientActivity. You can add methods or a constructor to an activity to pass in an id like 523584.
EventBus
This is an object the different parts of your program use to communicate. If you don't want to, you don't need to know very much about it - you can just plug it in where indicated in Google's documentation (that you linked to)
ClientFactory
This is a centralized object whose only responsibility is making other objects. You can also skip this concept if you want to simplify things - you'll just be missing out on the central organization of your objects. The advantage is that if you want to switch them out later for, say, a mobile version, or a mocked-up-for-testing version, you can do so all at once within a single place and the rest of your program doesn't have to change at all. You can also reuse the same objects easily when coordinating from a central place, so you don't have to re-create the whole main screen every time someone goes to #home.
Your Actual Program
All this stuff is just for navigation. Your models, views, and presenters are all set up in each Activitys start() method, which the framework calls when your app should navigate to a new place. In the start method you should start up your presenter (usually using a new instance) and start up your display (usually reusing an instance - the client factory is good for this). When you've created your display, you let the framework know by setting it as the widget for the AcceptsOneWidget that the framework passed into your start method.
This is incomplete, but a good supplement to the docs you mentioned: http://code.google.com/intl/de-DE/webtoolkit/doc/latest/DevGuideMvpActivitiesAndPlaces.html
I would also recommend you to carefully listen to the Google I/O presentations, they are a golden key to understand the GWT philosophy:
http://www.google.com/events/io/2010/
http://www.google.com/events/io/2009/
Specially these ones (try to keep a more holistic view of the MVP framework). They do not talk about the real GWT implementation but they give you basic knowledge of MVP. I still am an 8 months noob, so from noob to noob :)
Ray Ryan's overview of the MVP paradigm. Great resource (it was an enlightening for me).
http://www.google.com/events/io/2009/sessions/GoogleWebToolkitBestPractices.html
http://www.google.com/events/io/2010/sessions/architecting-production-gwt.html
Daniel Danilatos's testing for GWT. Here you will understand why all the fuzz for MVP!
http://www.google.com/events/io/2010/sessions/gwt-continuous-build-testing.html

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

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.