tags:

views:

747

answers:

10
+11  Q: 

Why use MVVM???

Okay, I have been looking into MVVM pattern, and each time I have previously tried looking into it, I gave up for a number of reasons:

  1. Unnecessary Extra Long Winded Coding
  2. No apparent advantages for coders (no designers in my office. Currently only myself soon to be another coder)
  3. Not a lot of resources/documentation of good practices! (Or at least hard to find)
  4. Cannot think of a single scenario where this is advantageous.

I'm about to give up on it yet again, and thought I'd ask to see if someone answer the reasons above.

I honestly can't see an advantage of using this for a single/partner coding. Even in complex projects with 10's of windows. To me the DataSet is a good enough view and binding like in the answer by Brent following question

Could someone show an example of where using MVVM pattern would of saved time when compared to XAML DataBinding.

100% of my binding is done in XAML at the moment. And therefore I don't see the point of the VM as its just extra code behind that I need to write and depend on.

EDIT:
After spending the afternoon researching about MVVM I have finally found something that made me realise the true benefits of it from this answer.

+2  A: 

There are a lot of good things about MVVM, but maybe the most important thing is the ability to test your code (Unit testing the ViewModels).

The lack of connection between the view and viewmodel really helps the loose coupling as well. It becomes really easy to reuse the components you code.

Svetlozar Angelov
Fair enough. Testing it would be easier..... or at least be more meaningfull. Personally I can't think of a test I would want to do on the ModelView that I couldn't do on the DataSets
LnDCobra
Very simple example: You can have a property for a button's enabled state and then bind the button's IsEnabled property to this property in the ViewModel. Now, you can unit test whether your logic of enabling/disabling the button is correct. Tell me how you do that in your DataSet. ;)
gehho
+12  A: 

It helps you seperating GUI and program logic; mixing them can result in very hard to maintain applications, especially when your project grows with time.

gammelgul
+1 I've maintained projects that do 100% XAML data binding. The separation gammelgul speaks of would have helped significantly.
Onion-Knight
+11  A: 

Implementing patterns and following best practices often feels like a pain and a pointless pursuit. But you will become a convert when months down the road your boss asks you tweak a feature. You will actually be able to follow your own code and fulfill the requirement with two lines of code rather than spending weeks trying to figure out how you did what you did in the first place before even trying to add new features.

Follow up: Patterns and best practices will actually slow down initial development and that's often a hard sell to management and engineering alike. The payback (ROI in biz terms) comes from having well-structured code that is actually maintainable, scalable and extensible.

As an example, if you follow MVVM properly, you should be able to make very drastic changes to the display logic, such as swapping out an entire view, with no impact on the data and biz logic.

A thought about using datasets for your model: (I have actually fallen for this too.) Datasets seem like a perfectly valid way to move around model data in an application. The problem comes in with how you identify the data items. Because your data is stored in rows and columns you have to perform look-ups by column name or index as well as having to filter for a particular row. These bits of logic mean having to use magic string and numbers in wiring logic in your application. Using a typed dataset would alleviate some of this issue but not completely and then you'd be moving away from MVVM and into tighter coupling between the UI and the data source.

Paul Sasik
Thats why I asked this question. It has happened to me before. I just need some motivation to stop being lazy and write some extra (in my opinion duplicate code)
LnDCobra
Could you give a real-life example of a feature that would take a long time to implement and using MVVM it would of been easy.
LnDCobra
For example, you can make Enum values appear much more user-friendly in the UI by converting the actual Enum value to a user-friendly string (maybe even localized). Or do you want your users to read values like "VeryHigh", "LightRed", ...?
gehho
Thanks, i have now decided to go with MVVM. Jason Dollinger did the best job anyone could of done explaining and demonstrating MVVM.
LnDCobra
+3  A: 
  • It is easier to work with designers (not programmers, just people using Blend)
  • Code is testable (unit tests)
  • It is much easier to change view without messing with the rest of the code
  • While you are developing UI you can mock model and develop your interface without running real service (just using mock data from model). Then you just flip flag and connect to the service.
Vladimir Kojic
A: 

You'll be happy in the long run if you use a pattern like MVVM for all the reasons the others have posted. Remember, you don't need to follow the pattern requirements word-for-word, just make sure you have good separation between your window (View) and your logic (code-behind).

ChrisNel52
+2  A: 

From Josh Smith's article on MVVM:

In addition to the WPF (and Silverlight 2) features that make MVVM a natural way to structure an application, the pattern is also popular because ViewModel classes are easy to unit test. When an application's interaction logic lives in a set of ViewModel classes, you can easily write code that tests it. In a sense, Views and unit tests are just two different types of ViewModel consumers. Having a suite of tests for an application's ViewModels provides free and fast regression testing, which helps reduce the cost of maintaining an application over time.

For me, this is the most important reason to use MVVM.

Before, I would have controls which mashed the view and viewmodel together. But a view essentially has mouse and keyboard events as input, and drawn pixels as output. How do you unit test something like that? MVVM makes this problem go away as it separates the untestable view from the testable viewmodel, and keeps the view layer as thin as possible.

Wim Coenen
A: 

Have a look at the Managed Extensibility Framework (MEF). As Ross explains here, it is better suited for small teams.

daRoBBie
+1  A: 

I'm still coming to grips with the pattern myself, but I do think it's valuable. The biggest challenge right now is that the approach is still quite new and therefore there is a lot of confusion and certain key components of the pattern are still awkward to implement. I've discovered a few things that have helped me a lot to make cleaner implementations of the pattern:

  1. I make heavy use of the RelayCommand from Josh Smith's MVVM Foundation. This makes the binding from View to ViewModel via Commands much cleaner.

  2. I use AOP to ease the pain of implementing INotifyPropertyChanged. I'm currently using Postsharp, though I believe there are other tools that can do this. If I hadn't discovered this, I probably would've given up by now, as the boilerplate code to implement it manually was really bugging me.

  3. I've had to invert my approach to how the software is implemented. Instead of having a dictator class that tells all of its minions what to do, which in turn use their minions, my software becomes more a matter of loosely coupled services that say:

    • This is what I know how to do

    • These are the things I need to have done

When you begin to structure your code in this way and use tools that make it easy to wire up the dependencies (there are a wide range of IoC frameworks to choose from), I've found it eases some of the awkwardness of MVVM, as you can reduce the boilerplate code associated with injecting the Models into the ViewModels and locating various View Services (such as displaying file dialogs) for your ViewModels to consume.

It's a huge investment to learn this different approach and, as with any major shift in implementation, productivity is much lower when you first start using it. However, I'm beginning to see some light at the end of the tunnel and I believe that, once I've mastered the messy details, my applications will be cleaner and much more maintainable.


To address the question about INotifyPropertyChanged via Postsharp, I use an Aspect based on the example here. I've customized it a bit for my use, but that gives you the gist of it. With this, I just tag the class [NotifyPropertyChanged] and all of the public properties will have the pattern implemented in their setters (even if they are auto-property setters). It feels much cleaner to me, as I no longer have to worry about whether I want to take the time to make the class implement INotifyPropertyChanged. I can just add the attribute and be done with it.

Dan Bryant
Please say more about using PostSharp to implement INotifyPropertyChanged. I'm just putting OnPropertyChanged in my base ViewModel class and I haven't found it burdensome yet. I've only used PostSharp for tracing method calls so far; how are you using it?
Robert Rossney
+2  A: 

From here:

Why should you, as a developer, even care about the Model-View-ViewModel pattern? There are a number of benefits this pattern brings to both WPF and Silverlight development. Before you go on, ask yourself:

  • Do you need to share a project with a designer, and have the flexibility for design work and development work to happen near-simultaneously?
  • Do you require thorough unit testing for your solutions?
  • Is it important for you to have reusable components, both within and across projects in your organization?
  • Would you like more flexibility to change your user interface without having to refactor other logic in the code base?

If you answered "yes" to any of these questions, these are just a few of the benefits that using the MVVM model can bring for your project.

Kent Boogaart
+1  A: 

Read the introduction into MVVM in this article

In 2005, John Gossman, currently one of the WPF and Silverlight Architects at Microsoft, unveiled the Model-View-ViewModel (MVVM) pattern on his blog. MVVM is identical to Fowler's Presentation Model, in that both patterns feature an abstraction of a View, which contains a View's state and behavior. Fowler introduced Presentation Model as a means of creating a UI platform-independent abstraction of a View, whereas Gossman introduced MVVM as a standardized way to leverage core features of WPF to simplify the creation of user interfaces. In that sense, I consider MVVM to be a specialization of the more general PM pattern, tailor-made for the WPF and Silverlight platforms.

..

Unlike the Presenter in MVP, a ViewModel does not need a reference to a view. The view binds to properties on a ViewModel, which, in turn, exposes data contained in model objects and other state specific to the view. The bindings between view and ViewModel are simple to construct because a ViewModel object is set as the DataContext of a view. If property values in the ViewModel change, those new values automatically propagate to the view via data binding. When the user clicks a button in the View, a command on the ViewModel executes to perform the requested action. The ViewModel, never the View, performs all modifications made to the model data. The view classes have no idea that the model classes exist, while the ViewModel and model are unaware of the view. In fact, the model is completely oblivious to the fact that the ViewModel and view exist. This is a very loosely coupled design, which pays dividends in many ways, as you will soon see.

Also the article explains why to use these gui patterns:

It is unnecessary and counterproductive to use design patterns in a simple "Hello, World!" program. Any competent developer can understand a few lines of code at a glance. However, as the number of features in a program increases, the number of lines of code and moving parts increase accordingly. Eventually, the complexity of a system, and the recurring problems it contains, encourages developers to organize their code in such a way that it is easier to comprehend, discuss, extend, and troubleshoot. We diminish the cognitive chaos of a complex system by applying well-known names to certain entities in the source code. We determine the name to apply to a piece of code by considering its functional role in the system.

Developers often intentionally structure their code according to a design pattern, as opposed to letting the patterns emerge organically. There is nothing wrong with either approach, but in this article, I examine the benefits of explicitly using MVVM as the architecture of a WPF application. The names of certain classes include well-known terms from the MVVM pattern, such as ending with "ViewModel" if the class is an abstraction of a view. This approach helps avoid the cognitive chaos mentioned earlier. Instead, you can happily exist in a state of controlled chaos, which is the natural state of affairs in most professional software development projects!

Tigraine