Applying the Open Closed Principle in Silverlight and WPF using MEF

In this post I want to show how MEF can be used to apply the Open Closed Principle where a class is open for extension but closed for modification.

In the Calculator application we have been building as part of the Silverlight refactoring series we could have used the code below to validate a users input.

By the way we are throwing exceptions because the application is using ValidatesOnExceptions.

public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception("Please enter a number");
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception("That's not a number");
        }
    }
}

If we wanted to add more validation rules to check the value cannot be negative or greater than a hundred we have to modify the CalculatorValidator class with two additional if statements.

public class CalculatorValidator
{
    public void ValidateNumber(string value)
    {
        if (String.IsNullOrEmpty(value))
        {
            throw new Exception("Please enter a number");
        }

        int number;
        if (!int.TryParse(value, out number))
        {
            throw new Exception("That's not a number");
        }

        if (number < 0)
        {
            throw new Exception("Number cannot be negative");
        }

        if (number > 100)
        {
            throw new Exception("That number is too big!");
        }
    }
}

and this pattern would continue every time you added a new rule, leaving the code as maintainable and stable as a wobbly tower!

Implementing the Open Closed Principle

Lets start by creating an interface for a validation rule

public interface ICalculatorValidationRule
{
    bool IsValid(string number);
    string ErrorMessage { get; }
}

Next we create a class for each validation rule by implementing the ICalculatorValidationRule interface

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNullOrEmpty : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        return !String.IsNullOrEmpty(value);
    }

    public string ErrorMessage
    {
        get
        {
            return "Please enter a number";
        }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsANumber : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        if (!String.IsNullOrEmpty(value))
        {
            int number;
            return int.TryParse(value, out number);
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return "That's not a number"; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsNotNegative : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) && number  < 0)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return "Number cannot be negative"; }
    }
}

[Export(typeof(ICalculatorValidationRule))]
public class ValidateValueIsLessThanHundred : ICalculatorValidationRule
{
    public bool IsValid(string value)
    {
        int number;
        if (int.TryParse(value, out number) && number > 100)
        {
            return false;
        }
        return true;
    }

    public string ErrorMessage
    {
        get { return "That number is too big!"; }
    }
}

An alternative to parsing the value to an integer in the validation rules to check the range would be to order how MEF composes the validation rules and ensure rule to validate the value is an integer is done earlier.

More information about this can be found in answer to this question on Stack Overflow – How does MEF determine the order of its imports?

ImportMany example in MEF

By using the ImportMany attribute on a collection in MEF we can iterate over all of the parts which export the ICalculatorValidatorInterface and check the value passes the validation rule by calling the IsValid method.

If the value is not valid a exception is thrown with the relevant error message.

The code below shows how the CalculatorValidator class would look

public class CalculatorValidator
{
    [ImportMany]
    public IEnumerable<ICalculatorValidationRule> CalculatorValidationRules { get; set; }

    public void ValidateNumber(string value)
    {
        foreach (var calculatorValidationRule in CalculatorValidationRules)
        {
            if (!calculatorValidationRule.IsValid(value))
            {
                throw new Exception(calculatorValidationRule.ErrorMessage);

            }
        }
    }
}

Couldn’t have done it without the extensibility of MEF

If we wanted to add a new validation rule, all we have to do is create another class which implements the ICalculatorValidationRule interface, add an export attribute and MEF will do the rest.

The CalculatorValidator class is now open to extension but closed for modification

SOLID design principles using MEF in Silverlight and WPF

In this part of the Silverlight refactoring series we will be looking at two ways the Managed Extensibility Framework (MEF) can help you refactor Silverlight or WPF applications to follow SOLID design principles.

The code used in this post can be downloaded here.

Apart from saying

through discovery and composition MEF gives you the ability to build applications which will be flexible enough for your every need

I won’t be covering what MEF is or how it works in depth in this post. Instead I recommend checking out the following blogs as well as the MEF site on Codeplex for some great tutorials.

What problem does MEF solve in this application?

The code below shows the Calculate method in the ViewModel.

public void  Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

Notice how Calculator class is created and used within the method. This means there’s no way of changing what class is used for calculations without modifying the code in the ViewModel.

In other words the calculator is tightly coupled to the ViewModel.

Composing, Initializing, Setting up, Bootstrapping, Configuring or whatever you want to call it in MEF

MEF works by using a catalog to discover extensions within assemblies. As the assemblies used in this application are in same XAP we can call the CompositionInitializer SatisfyImports method to automatically configure a container and compose the parts within it.

Looking at the class diagram for the application

Silverlight Class Diagram

we could decide

  • only the Calculator class will be an composable part
  • the ViewModel and the Calculator will be composable parts
  • the CalculatorPage, ViewModel and the class should all be composable parts

As this application only contains a single page we will go with the second option. This means we will be calling the CompositionInitializer SatisfyImport method in the CalculatorPage constructor as shown below

public CalculatorPage()
{
    InitializeComponent();
    CompositionInitializer.SatisfyImports(this);
}

Adding MEF Export Attributes

An export attribute is used to make classes and properties discoverable to the catalog and composable by the container.

As the Calculator class is used by the ViewModel we need to add an Export attribute to it. Because the Calculator implements the ICalculator interface we can use this as the contract type.

[Export(typeof(ICalculator))]
public class Calculator : ICalculator
{
public int Add(int firstValue, int secondValue)
{
    return firstValue + secondValue;
}
}

Similarly as the ViewModel is used by the CalculatorPage it also needs to be decorated with an Export attribute. As no contract is specified, MEF will use the fully qualified name of the type as the contract.

[Export]
public class CalculatorViewModel : INotifyPropertyChanged
{
    .....
}

An important thing to remember is that the export attribute is not allowed on the instance passed to SatisfyImports otherwise you will see the error below

MEF Export Error

Using MEF Property Imports

To use property imports in MEF we need to add a Calculator property to the ViewModel add decorate it with an Import attribute. In Silverlight MEF requires the property to be public.

[Import]
public ICalculator Calculator { get; set; }

The Calculate method in the ViewModel uses the property like this

public void Calculate()
{
    Result = Calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

In the code behind of the CalculatorPage we need to add a CalculatorViewModel property, decorate it with an Import attribute and set it as the data context.

public partial class CalculatorPage : UserControl
{
    [Import]
    public CalculatorViewModel CalculatorViewModel { get; set; }

    public CalculatorPage()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
        DataContext = CalculatorViewModel;
    }
}

If we run the application as it is MEF composes all the parts of the application and we are able to add numbers together… which is good but not great because I don’t recommend you should build applications only using property imports.

Using MEF Constructor Imports

I always try to follow the SOLID design principles whenever I’m developing applications.

The D in SOLID design principles stands for Dependency Inversion Principle.

One of the first things you should be taught when learning test driven development or even good coding practices is how SOLID design principles will help you create applications that are easier to develop, configure, maintain and unit test.

See my blog post ‘How to write better unit tests using RhinoMocks and stubs‘ for an example.

The good news is MEF supports constructor imports.

Using the ImportingConstructor attribute the CalculatorViewModel now takes in a Calculator in its constructor as shown below

[ImportingConstructor]
public CalculatorViewModel(ICalculator calculator)
{
    _calculator = calculator;
    ...
}

and the calculate method uses the calculator like this

public void Calculate()
{
    Result = _calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

Take care not to over engineer

So what about the importing the ViewModel in the CalculatorPage? We could stick to using a property for the ViewModel or pass it in the ViewModel constructor (in which case the call to CompositionInitializer SatisfyImports method will have to done in the App.xaml code behind).

I would be inclined to leave it as it is. Because we want to be able to unit test the ViewModel it makes sense to use importing constructors so we stub out the calculator.

Are we ever going to unit test the CalculatorPage? Probably not, and if we do need to, it’s not a major refactoring task.

In any case thanks to MEF the ViewModel can be changed without modifying the code behind for the CalculatorPage.

So what have we achieved?

By using SOLID design principles and MEF we have managed to remove the tight coupling between the ViewModel and the Calculator.

There is a lot of discussion about what MEF is in the development community. Despite numerous claims and comments that it’s not a dependency injection framework, I can’t help thinking it takes a step closer to being one with each release.

The last thing I’ll say about MEF is that

the number of options you have of using MEF is either impressive or confusing depending on what side of the fence you sit on

If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications.

So if you’re thinking, what if there’s an exception converting a string into an integer, check out the post ‘Validation in Silverlight and WPF using ValidatesOnExceptions‘ which shows one approach in solving this problem using exceptions.

How to Apply the Single Responsibility Principle to View Models in Silverlight and WPF

When you’re using the MVVM pattern with WPF or Silverlight it’s very easy to a have ViewModels that do too much.

In this part of the Silverlight Refactoring series we will convert a ViewModel with multiple responsibilities so that it adheres to the Single Responsibility Principle (SRP).

The code used in this post can be downloaded here.

Why should you care?

Currently the ViewModel looks like this

using System;
using System.ComponentModel;
using System.Windows.Input;

namespace SilverlightCalculator
{
    public class CalculatorViewModel : INotifyPropertyChanged
    {
        private string _firstValue;
        private string _secondValue;
        private string _result;

        private readonly ICommand _calculateCommand;       

        public event PropertyChangedEventHandler PropertyChanged;

        public CalculatorViewModel()
        {
            _calculateCommand = new RelayCommand(Calculate){IsEnabled = true};
        }

        public void Calculate()
        {
            Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();
        }

        public string FirstValue
        {
            get { return _firstValue; }
            set
            {
                _firstValue = value;
                OnPropertyChanged("FirstValue");
            }
        }

        public string SecondValue
        {
            get { return _secondValue; }
            set
            {
                _secondValue = value;
                OnPropertyChanged("SecondValue");
            }
        }

        public string Result
        {
            get { return _result; }
            private set
            {
                _result = value;
                OnPropertyChanged("Result");
            }
        }

        public ICommand CalculateCommand
        {
            get { return _calculateCommand; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

As you can see the logic to add two numbers is in the Calculate method of the ViewModel.

Therefore the ViewModel is responsible for calculating two numbers.

A ViewModel without separation of concerns is difficult to test, maintain and contains code you can’t reuse.

Although we’re only adding two numbers here, brushing the issue under the carpet will have consequences later down the line.

For example in addition to adding numbers what if another developer was given the task of storing the result in a database.

If the ViewModel was as it is now, with no separation of concerns, there is a chance they would put the code to store the value in the calculate method like this

public void Calculate()
{
    // Calculate result
    Result = (Convert.ToInt32(FirstValue) + Convert.ToInt32(SecondValue)).ToString();

    // Store value in database
    DatabaseConnection connection = new DatabaseConnection();
    DatabaseCommand command = new DatabaseCommand("TSQL TO STORE RESULT", connection);
    command.ExecuteNonQuery();
}

Now the ViewModel would be responsible for two things. Next it would be three and this would continue until someone decides to separate the concerns or it gets to a stage where it’s impossible to work with let alone read.

Refactoring the ViewModel to follow the single responsibility principle

Let’s start by creating a class for calculating numbers.

public class Calculator
{
    public int Add(int firstValue, int secondValue)
    {
        return firstValue + secondValue;
    }
}

Notice how the parameters passed to the method are integers, the calculator doesn’t accept string values.

What we are saying here is while it’s acceptable for the ViewModel to use strings for storing numbers the domain layer (or business logic if you prefer) does not.

In other words the add method does nothing more than add two numbers together. Validation should be handled elsewhere.

This makes the unit tests for the calculator very easy to write

[TestFixture]
public class When_calculating_numbers
{
    [Test]
    public void Should_be_able_to_add_two_numbers_together()
    {
        // Arrange
        Calculator calculator = new Calculator(); 

        // Act
        var result = calculator.Add(5, 5);

        //Assert
        Assert.That(result, Is.EqualTo(10));
    }
}

The code below shows how the ViewModel could create an instance of the Calculator class and call the Add Method. Notice how I say could and not should. We’ll see why later in the series.

public void Calculate()
{
    Calculator calculator = new Calculator();
    Result = calculator.Add(Convert.ToInt32(FirstValue), Convert.ToInt32(SecondValue)).ToString();
}

So what have we achieved?

As good boy scouts we have ‘left the ViewModel cleaner than we found it’.

By following the single responsibility principle we have created a ViewModel which is a better canvas for other developers to work with.

If you have arrived here from a search engine, this post is part of series about refactoring Silverlight applications. So if you’re thinking why is the calculator class tightly coupled to the ViewModel? Find out how this can be resolved by applying SOLID design principles using MEF in Silverlight and WPF.

Page 1 of 212