Monday, 25 January 2010

Code Complexity and Prism

I've recently had to review a number of problem areas of a large Prism project.  In the course of review, I had a number of realisations regarding design patterns, WPF and code complexity.  We use MVVM and MVC design patterns throughout our project.  Not surprising, many of our problem areas were related to divergence from these patterns.

In our implementation of MVVM we strive to have a complete decoupling of our Xaml views and any business logic.  So, finding views riddled with code-behind indicated a lack of understanding of:

  1. The MVVM design pattern, or
  2. The benefits of code separation

Or as I was to find out, a limited understanding of Xaml.  The view in question utilised over ten custom converters.  Not that converters are inherently evil, however, these converters were being used where Triggers or Data Binding could have easily gotten the job done.  But, if one is unfamiliar with these, they tend to use techniques they are familiar with -- in this case, IValueConverter.  Poor use of custom converters effectively becomes "hidden code-behind," and is difficult to debug and test.

Additionally, I found the ViewModel being underused and misused, providing a sparse selection of high level properties for binding.  This, in part, prompted the excessive use of custom converters.

The offending code-behind was an unusual solution brought about by a lack of Xaml know-how.   All of this code could have been expressed using Xaml.  Conclusion: Knowing a little about Xaml can reek havoc on a well-structured Prism project.

The hallmark of these decisions is code complexity, your first clue things have gone astray.

After much refactoring, including the removal of all the custom converters, the code-behind and reworking the ViewModel, the whole area straighten out and was greatly simplified.  It was a prime example of the power and importance of design patterns in maintaining good form and structure.

No comments: