by Geert
17. January 2012 20:22
Who would even thought this post would come from me, but today I saw a tweet that made me very, very unhappy… It was something like this (don’t want to quote people by name, everyone has a right to an opinion):
“How nice, my view models are completely auto generated…”
Let me explain (or at least try to) why bothers me so much about this. MVVM is a good pattern, so good that I decided to write a framework for it (called Catel). I like it and use it in all my applications. Below are the reasons why I like MVVM:
- Testable view logic (because you do not use any UI elements in your VM)
- Separation of concerns
- Protection of your models
- It’s it the pattern of the century!
The last reason is nonsense, but it seems that everyone is just using MVVM because it is MVVM. The reason why you *should* be using MVVM is because you are writing logic of a view or to protect a model.
As soon as you see words as “auto-generated”, “automatic”, etc in a view model, it is WRONG. And why? Because you can bind directly to the model as well (because that is all an “auto-generated” VM can do), saves you a lot of performance. One on one bindings which create an additional layer called view model is not fancy and should be avoided at all cost.
So, think again why you have started using MVVM and keep asking yourself the following questions:
- Do I want to be able to unit test my view logic and am I actually doing that?
- Do I want a clean separation of concerns (and is it separated, or am I using DependencyObject or any other UI elements in my view model)?
- Do I want to protect my models by exposing only a set of the properties to a view?
If the answer to all those questions is no, stop using MVVM. Seriously, just code everything in your code behind, add dependency properties to your “view model” and do something like this:
1: public MyView()
2: {
3: InitializeComponent();
4:
5: DataContext = this;
6: }
f875c9c4-09a4-4980-a83b-f1b16834b682|5|5.0
Tags: mvvm
MVVM