EDITING BOARD
RO
EN
×
▼ BROWSE ISSUES ▼
Issue 14

MVVM design pattern

Andrei Moldovan
Software Developer
@Business Logic Systems Ltd.



PROGRAMMING

Each programmer tries to be as organized as possible when it comes to writing code. Each team organizes the project so that it will be easy to maintain and understand by the new members in the team. This can be the result of the use of design patterns. We know that there are a lot of code organizing rules like these and that once we choose one of them it is very difficult and costly to change. However, it is important for the programmers to be up to date when it comes to these design patterns in order to have a maximum benefit from using them.

Model-View-Viewmodel (MVVM) is a design pattern used in the software industry which was first introduced by Microsoft as a way to customize the model introduced by Martin Fowler. It seems that Microsoft was using MVVM for the projects that they were developing, like Expression Blend, even when the core of the WPF platform was under development. Based mostly on the Model-View-Controller (MVC) model, the pattern is addressed in particular to the user interface developers of the modern platforms ((HTML5, Windows Presentation Foundation, - WPF and Silverlight), in the projects where there is a developer that is specialized on this thing, having tasks that are different from the ones of a regular developer (which handles mostly the business logic and the interactions with the server).

Architecturally, the pattern is composed of 3 essential parts, which can be deduced from its name: a Model, a View and a ViewModel. This structure resembles the one of the MVC, but offers the advantage of the ease of use of XAML and Windows Presentation Foundation, through data binding as close to the model using XAML, ViewModel and any check of the data at the Business level used to validate the data before it is displayed on the GUI. The Model refers to the actual data which the application works with, but also to the access layer to these data. For example, in the model, the objects that read from the database information about a person are declared. The Views, as in the classic case, refer to the visual part that will be displayed on the graphic interface, like buttons, windows and other controls. These do not contain the business logic part. The big advantage here is that a designer can handle the graphic part of the application working just on the views, while the logic from behind remains unchanged. The ViewModels can be compared to models for the views, more precisely they refer to an abstraction of the view but they also have the function of binding data between the view and the model. They can be compared to the controls from the MVC design pattern but with more specialized aspects, such that they change the information from the model format to the view format and pass the commands from the view to the model. The viewmodels expose the properties and the commands, working with a form of data that is rather conceptual. The model on the other hand works with the real state of the data. There are debates related to the class behind the view. Most specialists suggest that it should contain just the InitializeComponent() method in the case of WPF and Silverlight, but in some cases it"s not worth moving the methods in the viewmodel.

The View communicates only with the ViewModel, whereas the ViewModel is seen as an intermediary point between the View and the Model. Also the Model is the only one that interacts with the database. This model makes sense in practice only if it is used in combination with a database, otherwise the data objects like the entities from EDMX or Linq do not make sense in this context. A diagram of this design pattern can be seen in the figure below.

Other functionalities that make this pattern be used so frequently are the data templates and the system resources. The templates apply Views over the objects of a ViewModel. Programmers can declare them in XAML and let the system resources locate them automatically and then apply these templates at runtime.

Because this pattern can sometimes be hard to implement from scratch, some platforms were developed to help programmers implement it, like MVVMLight or Caliburn. I personally recommend the last one because it offers the advantage of automatic recognition of the View by the ViewModel, without the need of an auxiliary class to do this thing.

Let"s consider a simple example with an application that displays information about products from the database (name, price, id). In the Model we need to have the data access part. The way in which these will be accessed remains to the latitude of the programmer. This class will implement INotifyPropertyChanged and will contain the 3 properties, each having on the setter OnPropertyChanged("Property") to signal the change in value of the property. Special attention needs to be given to the name of the property because this will be passed on as string.

The ViewModel will contain all the part that the user needs to interact with the application. All the operations on the data, like list sort, delete of items from the list and others must be written here. In this case, 2 commands are declared: GetProduct and SaveProduct which will be used to bring an object from the model in the view and to save a product. These are of ICommand type and have a syntax like the following:

public ICommand SaveProductCommand{
   get{
     if (_saveProductCommand == null) {
       _saveProductCommand = new RelayCommand(
                    param => SaveProduct(),
                    param => (CurrentProduct != 
              null)); }
           
      return _saveProductCommand;
      }
}

The RelayCommand class is also located here, which is essential for the MVVM to function. It contains a command that will be executed by other classes to run code in the base class by invoking of delegates.

The View is the part that defines how the application will look. Also 2 DataTemplates must be declared, one for the Model and one for the ViewModel:

MainWindow app = new MainWindow();
ProductViewModel viewModel = 
                    new ProductViewModel();
 
app.DataContext = viewModel;
app.Show();

So when should we use this model? Although its structure is a logical one and it offers good organizing of the code, it is not suitable for any type of project. If we have a project that has a graphic interface which is not very complex, it is not justified to use MVVM because the code can be written in the class behind. Also, some programmers do not recommend using this pattern if unit testing will not be done. Due to the fact that the easiness of writing unit tests is one of its advantages, it is preferred that the pattern is used only with unit tests. It is unproductive, and thus not recommended the use of this pattern in a simple "Hello world!" application. Any software developer can understand a few lines of code, even if they are not very organized. However, as the number of code lines increases, so does the functionality.

Besides the disadvantages mentioned above, there is also the fact that in some cases it can be difficult to design the ViewModel in order to obtain the degree of generality needed. Also debugging the data binding is more difficult compared to the classic methods where the code is written in the class behind.

In conclusion, MVVM offers certain advantages like the separation of the view from the business logic and the easiness in writing unit tests, but programmers must be careful if this design pattern is suitable or not for their project.

VIDEO: ISSUE 109 LAUNCH EVENT

Sponsors

  • Accenture
  • BT Code Crafters
  • Accesa
  • Bosch
  • Betfair
  • MHP
  • BoatyardX
  • .msg systems
  • P3 group
  • Ing Hubs
  • Cognizant Softvision
  • Colors in projects

VIDEO: ISSUE 109 LAUNCH EVENT