Thursday, February 26, 2009

Anti-Pattern: The god object

Because it’s easier to recognize evil if you have a mug shot, here’s one simple for all of you. The god object is a class that knows too much. It’s a severe violation of the Single Responsibility Principle and probably a lot of the other principle of SOLID depending of the implementation.

A basic principle in programming is to divide a problem in subroutines to make the problem easier to solve. It’s also know as “divide and conquer”. The object becomes so aware of everything or all the objects become so dependant of the god object that when there is a change or a bug to fix, it become a real nightmare to implement.

I tend to call those objects “Death Stars”. Death Star Why? Because just like the death star, if someone get to mess up with the core, it will explode. In fact, any modification to this god object will cause ripple of changes everywhere inside the software and will end in lots of bugs.

You can easily recognize of these object by the fear any developers have when getting near it.

So how to solve it? By refactoring of course! The goal is to separate in as much subroutine as possible. Once this is done, you move those subroutines to different classes. Of course, trying to follow the SOLID principles will definitely help.

Resolving a god object is of course really different depending on how omnipotent your god object is. But one thing for sure, you have to separate the “powers” (read: responsibility) and make sure that Single Responsibility Principle is applied.

Submit this story to DotNetKicks

Wednesday, February 25, 2009

We all produce code that we really aren’t proud of

Everyone produce code. Some peoples give birth to some beautiful, elegant and maintainable code sometime in their career. But pretty much all developers will one day or another give code that is so horrible, inelegant and un-maintainable.

I’m trying as much as possible to separate concerns inside my application so that I don’t have to care about problematic maintenance. I’ve recently had to review some code I did more than a month ago and… I’m not proud. I’m really not proud of the code I saw. It seems that every once in a while we write some code that we won’t be proud of.

Of course, we improve our coding skills every day and every time we encounter new technology and new idea. Hell, I like the SOLID principles and the TDD ideas. I love the concept of separation of concerns and modularization of an application. So how come I wrote this code?

I can’t remember exactly why honestly. Maybe I was rushed or I wanted to rush through it. How knows… what is important however is to know that the code that you wrote taste like a cheap wine. It’s important to take a note of it and make sure to “maintain your code garden”. This is at the moment that the title of my blog actually makes sense. Even with the best intention, code quality decay and if nothing is done, you finish with a half rotten application that nobody will care about.

So what to do about it? Make sure to improve the quality of existing code everyday. If we write bad code 10% of the time (number that I just picked from the top of my head) and good code 90% of the time, imagine if we take only a few hours per week to correct mistakes.

You probably won’t have the time to fix it. Who does? But there will be a day where you will finish an hour early and that you will wonder if you should start implementing a new feature or go home early. If you took note of those classes that need improvements, you could easily take this hour to maintain your code garden and be proud of the code that you did.

So, the first “time off” that I have will be used to fix this part of code that I’m not proud of.

Anyone else who wrote some shameful code?

Submit this story to DotNetKicks

"Utilisations des mocks avec Moq" - Using mocks with Moq

For those who attended my presentation at the Montreal .NET User Group, here is a list of links that I mentioned inside my presentation:

Submit this story to DotNetKicks

Monday, February 23, 2009

Model View Presenter Revisited

The MVP pattern is a pattern that came into being in the early 1990s by Taligent. This pattern is mostly used inside WinForms and WebForms.

The View normally don’t do anything. The official implementation is described as the following.

The view instantiate the presenter with an instance of itself. The constructor parameter of the presenter must be an interface of the view. When events of the view happens, they must call the presenter without any parameter/return value. If the presenter need data, the presenter will get the data from the view interface without the view giving the data directly. Changes to the view must be done through the presenter.

Of course, this is a literal implementation from 1990. Of course, today we have more advanced paradigm that works quite nice. What is interesting is, with proper data binding, that we can change the value on the views without even calling methods of the view.

It is possible to add a databinding on a property of the presenter. Once the databinding is done, it’s possible to just change the presenter’s property to fire events on the view that will automatically updates the control.

It removes some implementation details of the MVP and make the pattern easier to implement.

Need a sample? Here it goes to implement an “auto-notify” property when it change inside a presenter:

public class MyPresenter : IPresenter, INotifyPropertyChanged
{
   private readonly IView view;
   private int randomNumber;

   public int RandomNumber
   {
       get { return randomNumber; }
       set
       {
           if (randomNumber == value) return;

           randomNumber = value;
           RaiseEvent("RandomNumber");
       }
   }

   #region Implementation of INotifyPropertyChanged

   // custom method to ease the change of event
   public void RaiseEvent(string propertyName)
   {
       PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
   }

   public event PropertyChangedEventHandler PropertyChanged = delegate { };

   #endregion

   public MyPresenter(IView view)
   {
       this.view = view;
       this.view.InitializeBindings(this);
   }

   public void GenerateRandomNumber()
   {
       Random rnd = new Random(DateTime.Now.Millisecond);
       RandomNumber = rnd.Next(0, 100);
   }
}

This will raise an event every time that a DIFFERENT value will be assigned to the property RandomNumber or when the event is fired. Now for the view, it look like this:

public partial class frmMain : Form, IView
{
   private readonly IPresenter presenter;

   public frmMain()
   {
       InitializeComponent();
       presenter = new MyPresenter(this);
   }

   public void InitializeBindings(IPresenter currentPresenter)
   {
       textBox1.DataBindings.Add("Text", currentPresenter, "RandomNumber", false, DataSourceUpdateMode.Never);
   }

   private void button1_Click(object sender, EventArgs e)
   {
       presenter.GenerateRandomNumber();
   }
}

The method InitializeBindings is called in the constructor of the presenter and will ensure that the binding are made only once. This will NOT require additional methods inside the view to assign the generated number inside the TextBox. This implementation respect the model definition while using the latest binding technology of .NET.

This reduce the amount of useless method while keeping the framework in charge of the bindings.

Here is the resulting interfaces from the implementation:

public interface IPresenter
{
   int RandomNumber { get; set; }
   void GenerateRandomNumber();
}

public interface IView
{
   void InitializeBindings(IPresenter currentPresenter);
}
Submit this story to DotNetKicks

Sunday, February 22, 2009

Part 3 – Advanced mocking functionalities of Moq

See also: Part 1 – Part 2

When you have some simple scenario like “when the method “GetTax” is called, return 5$” it’s a simple scenario that a lot of mockers will see. However, there is some rarer scenario that people will wonder how to do it.

One of those scenario is with event handlers. The scenario would be like “if a Product is added to a ShoppingCart, a ProductAdded event should be fired”.

Let’s start with the basic class bellow which implement our scenario:

namespace MoqSamples
{
   public interface IProduct
   {
       bool IsValid { get; }
   }

   public class ProductEventArgs : EventArgs
   {
       public ProductEventArgs(IProduct product)
       {
           Product = product;
       }

       public IProduct Product { get; private set; }
   }

   public class ShoppingCart
   {
       private readonly List<IProduct> Products = new List<IProduct>();
       public event EventHandler<ProductEventArgs> ProductAdded = delegate { };

       public void Add(IProduct product)
       {
           if (product.IsValid)
           {
               Products.Add(product);
               ProductAdded(this, new ProductEventArgs(product));
           }
       }
   }
}

Event Handlers

What we want to test here, is every time we add a valid product an event ProductAdded should be fired.

I have played with Moq a bit trying to get it to work with ShoppingCart. As I tried to mock the event, I tried to create mocks and use the instructions on Moq site but wasn’t able to make it happen. If I tried to mock the class itself it wouldn’t allow me to do expectations even if I extracted an interface out of it. If I mock the interface, I lose the logic inside my class. I was thinking about creating a mocked event handlers and see if it ever get called but… you need a mock to create a mocked event handler. With this, we’ll have to wait for Moq 3.0 (which is in beta at the moment of writing this article). Here is the test I came up with that didn’t work :

[Test]
public void Adding_A_Valid_Product_Fire_Event()
{
   // Setup our product so that it always returns true on a IsValid verification
   Mock<IProduct> product = new Mock<IProduct>();
   product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

   // setup an event argument for our event
   ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

   // setup a mocked shopping cart to create our mocked event handler and a true shopping cart to test
   Mock<ShoppingCart> mockedShoppingCart = new Mock<ShoppingCart>();

   //creating the event a mocked event
   MockedEvent<ProductEventArgs> mockedEvent = mockedShoppingCart.CreateEventHandler<ProductEventArgs>();
   mockedShoppingCart.Object.ProductAdded += mockedEvent;
   mockedShoppingCart.Expect(shopping => shopping.Add(product.Object)).Raises(mockedEvent, productEventArgs).Verifiable();

   //making the test
   IShoppingCart myShoppingCart = mockedShoppingCart.Object;
   myShoppingCart.Add(product.Object);

   mockedShoppingCart.Verify();
}

And here is my simple fix to test this:

[Test]
public void Adding_A_Valid_Product_Fire_Event()
{
   // Setup our product so that it always returns true on a IsValid verification
   Mock<IProduct> product = new Mock<IProduct>();
   product.Expect(currentProduct => currentProduct.IsValid).Returns(true);

   // setup an event argument for our event
   ProductEventArgs productEventArgs = new ProductEventArgs(product.Object);

   // creating our objects and events
   ShoppingCart myShoppingCart = new ShoppingCart();
   bool isCalled = false;
   myShoppingCart.ProductAdded += (sender, e) => isCalled = true;

   // Testing the Add method if it fire the event
   myShoppingCart.Add(product.Object);

   // make sure the event was called
   Assert.AreEqual(isCalled, true);
}

Way more small and more efficient with the mocking. Sometimes, it’s better not to try to bend the framework and find the shortest solution that works.

Moq Factories

Moq have factories to help centralize the mocking configuration. The only two configuration available is CallBase and DefaultValue. Every mock created with the factories will allow you to reuse the configuration and reduce the amount of line for setting up the mock.

Here’s a sample for the factory initialization:

[Test]
public void Moq_Test_With_Factories()
{
   // Initialize factories with default behaviours
   MockFactory mockFactory = new MockFactory(MockBehavior.Default);

   // Setup parameters for mocking
   mockFactory.CallBase = true;
   mockFactory.DefaultValue = DefaultValue.Mock;

   // create mocks with the factory
   Mock<IProduct> product = mockFactory.Create<IProduct>();
}

This is of course really easy but… what about the parameters?

CallBase

CallBase is defined as “Invoke base class implementation if no expectation overrides the member. This is called “Partial Mock”. It allows to mock certain part of a class without having to mock everything.

DefaultValue

There is 2 possible values here. One of them is “Empty” which return default value of the class. The one used in the example is “Mock” which allows “automocking”. If a property is mockable, a mock is automatically returned.

Constructor

The constructor of the MockFactory needs a MockBehaviour parameter. 3 values are possible, Default, Loose and Strict.

Strict mock makes mocked object throw an exception for every call to a mocked object that doesn’t have an expectation. Loose (which is also Default) will always return default values or empty arrays or null.

By using the factory properly, it’s possible to set one style of mocking and reuse theses settings without having to rewrite 1 or 2 more lines per mock.

Submit this story to DotNetKicks