Monday, October 28, 2013

Why and When of MVVM - MVVM series 1 of n

Developing software is HARD. In fact, I would say, it's very HARD. Patterns and Architectural Structures help, but... it’s still hard. Like any other architectural structures, MVVM is also a structure with a set of guidelines and NOT a set of rules.

In the past few months, I came across various forums and online discussions, where people often ask "Why should I use MVVM? It seems like it complicates things" and I realized that MVVM is very difficult to learn for beginners who have very little knowledge of design patterns and frameworks.

As of today, if you will search MVVM in any of the search engines, you will get lot many articles written by the extremely knowledgeable through to the novices, and it is really hard to sort the wheat from the chaff.

Apart from this, there are lot of resources which mention few points and miss out others, which may be very conflicting for those beginners as well as for some experienced programmers. I'm not going to call them bad programmers, in fact they could be good programmers or say, they could be great programmers. Even if you are bad programmers, don't worry, I am not going to hang you for it.

Well, jokes apart. Regardless of all arguments, today I am not planning to introduce philosophy, but my plan is to put all the relevant concepts together in a single post, to make MVVM simple to understand and straightforward to implement. MVVM is far simpler than people make it out to be.

The most popular reason many developers put forward for MVVM is that "its main purpose is to do unit testing for presentation code". To some extent, this is true but this is not the only reason one should invest in MVVM. There are number of benefits this structure brings to WPF, Silverlight, Windows Phone as well as Windows Store application development process. Let's figure out the need of MVVM in layman language, which will help everyone to understand the concept in a much easier way:
  • Do you have a team for developer, designer and tester, and want all of them to work simultaneously on the same project or module?
  • Do you want to have a reusable components within the project or organization?
  • Do you want your UI and Presentation logic to be loosely coupled?
  • Do you want independent unit testing of your Presentation logic?
  • Do you have frequent changes in your UI due to requirement change?
  • Do you want reusable code between WPF, Silverlight, Windows App or let's say you want to share your code between more than 1 type of applications? (Please note: This is not 100% sharing of code, but yeah you can say, it is close to 90%. I would say, it is better to have something, rather than nothing. Isn't it ?)
Well, if you answered, any of the above questions in YES, then we can go for MVVM. The list is not only this much, there are bit more benefits around MVVM. I have drawn the below list from several discussions, blogs, presentations as well as with my experience. So, let's gear up and have a look at those benefits:
  • The rousing dynamism behind using MVVM is the XAML based apps, which evolve around very nice concepts of databinding, commanding, dependency properties, etc.
  • MVVM provides proper layering of the view and the data. The data is not stored in the view but the view is only and only used for data presentation. View need not to be aware as from where and how the data is coming. So, even if our business logic is changing n number of times, it will not at all impact our view. 
  • Concurrent development – Other advantage of using MVVM is that during the development process, developers and designers can work more independently and concurrently on their components. The designers can concentrate on the view, and if they are using Expression Blend, they can easily generate sample data to work with, while the developers can work on the view model and model components.
  • SoC (Separation of Concern) - MVVM help us to achieve SoC, by putting presentation logic into ViewModel. MVVM is not an exercise to remove all the code from your XAML code behind files. Instead, MVVM intends to separate the logic you need to access and interact with your data from the logic you need to interact with your UI. For example, loading your data, validating your data, manipulating your data, and saving your data – that’s all part of the View Model. Conversely, running animations, responding to gestures, and adding the blink that makes your app stand apart – that’s part of the View. Beginners, please note, ViewModel is not the code-behind file. It is a separate class for writing UI related logic. I will touch more upon this, in my upcoming posts.
  • Loose Coupling - By using code-behind approach, it is very easy to create tightly coupled UI elements, but that sounds really very bad. At the same time, tightly coupled approach will lead to huge time-to-market because everything needs to be in sequence as developer and designer are totally dependent on one-another to finish their task. Creeping logic into your code behind – it is not rare for developers to relish the easiness of double-clicking Visual Studio’s designer and allowing a click event handler be created. MVVM guidelines will help developers/designers to write much more cleaner code in a very loose coupled way.
  • MVVM provides the ability of a developer and a designer to work on the view independently without risk of corrupting the other's work. In MVVM, no matter what the designer does to the view, the ViewModel code is untouched. And same is the reverse, no matter what the developer does to the ViewModel, the View is not affected. Isn’t it amazing???
  • Design time data support is one of the features I like the most. Once UI is ready, designer can test the UI by using any of the supported designer tools. One of the commonly used tools Expression Blend, in which the designers can test the UI with sample data and even simulate a fully functional data binding scenario.
  • Multiple views: MVVM is very well known for flexibility and loose coupling. The same ViewModel can be presented with multiple views. For example, if you want to show different-different type of UIs based on the user role, then it is really nice to have bonus from the MVVM. In this case, all the UI will have almost the same business logic and only the data representation is different. So, a single ViewModel can serve multiple views.
  • Automated unit testing: Separation of this view/logic separation also greatly improves automated unit testing of the presentation logic. One of the primary benefits of using MVVM is the unit testability of the codebase. Traditionally, software was developed with event handlers embedded right in the codebehind of the presentation. This tightly coupled approach of view to business logic can easily result in code that is difficult to maintain. With the MVVM and unit testing in place, the codebase can remain robust over the lifetime of the software, and the intent of the developer can be well documented in the unit tests which are written (so long as unit tests are kept up to date).
  • It is very much easy to change view without messing up with ViewModel due to loose coupling.
  • Maintainability - Why does maintainability matter? Maintainability is not the inverse of complexity. That’s because complexity can be controlled by following good patterns and architectural guidelines like MVVM. But without good patterns and guidelines, complexity is the logarithmic multiplier to headaches and troubles. I never mind picking up on a project that is well organized.
  • I hope, by this time, you might have got an idea about all the benefits that MVVM provides. Now, let’s check on when to use this useful structure.

    When to Use MVVM

    Now the biggest question is WHEN to use MVVM. Lot of people think that MVVM is what we use all the time. But when you are building a very small app, like a one page or a two page application, it might make more sense just to do things like an ad-hoc way of building an application, where you pick the XAML, put in the project, hitting some services, hooking up some events and pushing information on to your UI page, just manually. That is perfectly fine while dealing with small application. But where MVVM really comes in handy is, when we start building large applications, in which we have several different pages, where we need to manage data structures.
    While doing internet surfing, I found a statement which states, "MVVM only makes sense for extremely complex UI", or "MVVM always adds a lot of overhead and is too much for smaller applications". The real kicker was, "MVVM doesn't scale". In my opinion, statements like this speak to knowledge and implementation of MVVM, not MVVM itself. In other words, if you think it takes hours to wire up MVVM, you're not doing it right. If your application isn't scaling, don't blame MVVM, blame how you are using MVVM. Binding 100,000 items to a listbox can be just silly regardless of what pattern or practice you are following.
    Conclusion is, it’s Not All That Different and it’s Not That Hard. MVVM is, without question, one of the best things to ever come out of XAML development. MVVM separates the logic necessary to intermingle with the data from the logic necessary to intermingle with the UI. Where together, it makes a jumbled mess, separating it makes a sophisticated approach that is more effortlessly maintainable.

    Disclaimer

    So the quick disclaimer: This is MVVM as I know it, not MVVM as a universal truth. I’m not saying this is all you’ll ever need to know about MVVM, I’m saying if you know this, you can benefit from MVVM on any non-trivial application, while you’re learning more. I encourage you to share your thoughts, experiences, feedback, and opinions using the comments. If you feel something is incorrect, let me know and I'll do my best to keep this post updated and current.

    Ending Note

    MVVM is neither a template nor has any class. But there are plenty of conventions and plenty of framework candy to help MVVM implementations sail simply. XAML developers love MVVM, in fact, MVVM was invented by the original WPF creators. To that end, MVVM is lightweight, simple, and easy to learn. Best part is, it can be used with Silverlight, WPF, Windows Phone or any other XAML based application.

    References
    Jeremy's blog

3 comments: