Yet another MVVM and Opening/Closing of Dialog discussion - Code Behind
Why is having some code behind for doing simple operations such as opening
or closing a dialog a bad design choice when using MVVM? If not for code
behind, then where is the consistency for handling such a simple problem
such as opening a dialog in MVVM?
I know this subject has probably been beaten to death and using "Code
Behind" in WPF has been getting a lot bad rep over the years. I just want
to make my point here and hopefully it helps someone gain a different
perspective on the problem.
I think most people would agree that the MVVM pattern while a little
bloated encourages reuse and better testable code. Separating business
logic from the view is not a new concept but yet many people still don't
do it. MVVM and WPF makes this separation a bit easier through the
concepts of data binding and allows your ViewModels and business logic to
be tested independent of the view.
Where it breaks down is when the developer needs to do simple things like
opening or closing a dialog. Outside of MVVM, a developer could just
instantiate the view, assign the DataContext and call ShowDialog. But in
MVVM, a developer's first thought always goes to what's the common pattern
here for opening/closing dialogs through MVVM. And what do they do, they
take their question to Google/Bing/StackOverflow. And sure enough, they
find answers to their question but the problem is there is no consistency
here for doing such a simple operation. Some people want to use Mediators,
others a dialog service, and others want to bring in Prism. Just about
everyone has their own home grown implementation and all to accomplish
what? So that they can avoid having "Code-Behind"? To me that is just sad.
We've basically taken something that is so simple to do and added
abstractions and indirection to try to solve the problem. The gain is so
small it's not even worth it. Without going through this level
indirection, you can still reuse your ViewModels with other Views, and you
can still test your ViewModels in isolation. The only thing you don't get
to test is a couple lines of code that opens or closes a dialog.
The MVVM and unit testing purists will think this is blasphemy. But
remember, in the end, it's really your decision on how complex you want to
make your application. To me the simple solution is usually the right
solution.
No comments:
Post a Comment