Decaying Code

Where code comes to die

About the author

Maxime Rouiller is a passionate .NET technology specialist, working for 7 years in large software development, advocating Agile and TDD. Aware of the latest technological trends, he intervenes as a specialist in the .NET Montréal usergroup and acts regularly as a speaker for Web Form programmers on the MVC platform.

View Maxime Rouiller's profile on LinkedIn

Month List

TDD: How I applied TDD to a simple problem

A month or two ago I had to built a component that had to analyse a string a return some information out of it. The best result for this was a Regular Expression and I was sure. So I started writing what kind of input would be valid and which one should not be allowed.

When I started writing this code, I already read many blog posts about it and wanted to give it a try. Since I wanted a simple scenario which would easily be applied, when I had to parse this string I knew I had a simple problem to which I could apply it.

If anyone has ever worked with regular expressions, it is widely known that it's easy to make something match. However, it's really hard to make it match what you want and not what you don't want. For proof of that, try seeing how many regular expression there is to parse a phone number. The non-matches is as important as the matches.

So I started a test project and added my first test. The test was to test the perfect scenario. Of course the test didn't even compiled. I then proceeded to create the missing classes and made the test compile. Of course, all the class had the following inside them:

throw new NotImplementedException();

This ensured that the test "went red". I then proceeded to implement the minimum necessary to make it pass and make it "go green". And I kept on rolling until it worked in all my specified cases. Sometimes, previous tests went and failed. Sometimes, everything stayed green but I kept on going.

For experienced TDD-er it's common and normal. But for me, it was weird. I made sure to follow EXACTLY what it said. When it said "minimum necessary to make it pass", I made sure that I returned a constant if I could or proceeded to create/modify the regular expression as needed. And as I kept increasing my amount of test, the constant all went away, the regular expression got more precise and every time that I broke a test I came back to fix it. It's a weird feeling but when I gave my class for usage, it was working as perfectly as it could.

So why the ruckus? Because since I wrote this piece of code, I haven't seen one bug report. The code is perfect for what it is doing. When a bug will come my way, I'll try the TDD-er way of doing thing. Add a test that reproduce the bug and fix my code to make sure it works on all test.

Result of everything? One bug ridden class, 20 something tests and one developer who learned the essence of TDD.

I would love to get my teeth on more complex code now.


Permalink | Comments (0) | Post RSSRSS comment feed

Anti-Pattern: Anemic Domain Model

Here is an anti-pattern Martin Fowler will agree with. In fact, it's Martin Fowler that first described this anti-pattern in November 2003. Like Fowler said, it looks like a model, it smells like a model but there is no behaviour inside.

The basic symptom of an Anemic Domain Model is that at first blush it looks like the real thing. There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters.

The problem with the anemic domain model is that all the logic is not with the associated object. It's located in the objects that use them. See the problem? So unless you are using the objects that have the behaviours, having the anemic domain model won't bring you any good. In fact, they just getters and setters with barely enough behaviour to call them objects.

Of course, you gain a good separation of concerns and a gain in "flexibility" of behaviours if ever needed. You also gain the ability to generate those domain models from a modeling tools without having to break a sweat. If there is so many benefits, where's the catch?

3 times nothing! You just need to separate the business logic multiple time so that every part of the business get their own. Objects can't self validate since the validation logic is located outside of the object. Everyone need a reference to that specific model DLLs and any shared entities which increase the coupling of the classes. It also increase the code duplication since many part of the business will essentially reuse many parts that other part of the business need. Don't forget the maintenance! Since the business logic is spread across the business, all the common business logic will need to be updated all at once and validated against their respective service and validation. And that, is if this part of the business want to update. It's like dealing with many mini-companies within the same companies.

Got enough? So put some business logic inside your domain model and make it easy to understand. If a certain part of the business need so "special" behaviour, it will have to be incorporated inside the main domain model.

But what if you have to maintain an anemic domain model and you want to fix this anti-pattern? Of course you can always rewrite the software but it's an expensive solution. The solution is that every time a new requirements arrive, put it inside the domain model and DO NOT put it inside the many service class. This is what Greg Young described as "making bubbles". By making bubbles of great code that is going to be easy to maintain/reuse, and by maintaining the current system, you will finish by replacing everything.

Anything worth doing is worth doing well.


Permalink | Comments (9) | Post RSSRSS comment feed

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.


Permalink | Comments (3) | Post RSSRSS comment feed

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?


Permalink | Comments (0) | Post RSSRSS comment feed

"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:


Categories: mock | moq | presentation
Permalink | Comments (0) | Post RSSRSS comment feed

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);
        }

Categories: architecture | design | pattern
Permalink | Comments (0) | Post RSSRSS comment feed

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.


Categories: c# | mock | moq | unit test
Permalink | Comments (2) | Post RSSRSS comment feed

How to add custom build step to a TFS Server Build ?

Most of the time when you are creating a build script (TFSBuild.proj), you need to do some steps after the build. Wether it's creating an MSI for easier deployment, creating a VSI for a Visual Studio Add-in, or whatever if may be... you normally do a post build.

A post build event looks like the following inside the TFSBuild.proj :

<Target Name="AfterDropBuild">
        <CallTarget Targets="PostBuildStep" />
        </Target>

        <Target Name="PostBuildStep">
        <!-- Do something -->
        </Target>

When you only have 1 or 2 tasks and that one fails, it might be easy to find the one that failed. What if you have 8 to 20 tasks? It then becomes incredibly hard to find which one failed. What I've seen the most is normally some "<Message />" tags with some descriptive tasks. This is the equivalent of debugging with Console.WriteLine or Debug.Print.

What if you could know EXACTLY which task failed to run? Here is a way to add a custom build step to your TFS build which will allow you to easily know what crashed.

<Target Name="PostBuildStep">
        <!-- Create the build steps which start in mode "Running" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Message="Doing Something on a PostBuild Event" Condition=" '$(IsDesktopBuild)' != 'true' ">
        <!-- Return the ID of the tasks and assigned it to "PropertyName" -->
        <Output TaskParameter="Id" PropertyName="PostBuildStepId" />
        </BuildStep>

        <!-- Do something -->

        <!-- When everything is done, change the status of the task to "Succeeded" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Succeeded" Condition=" '$(IsDesktopBuild)' != 'true' " />

        <!-- If an error occurs during the process, run the target "PostBuildStepFailed" -->
        <OnError ExecuteTargets="PostBuildStepFailed" />
        </Target>


        <Target Name="PostBuildStepFailed">
        <!-- Change the status of the task to "Failed" -->
        <BuildStep TeamFoundationServerUrl="$(TeamFoundationServerUrl)" BuildUri="$(BuildUri)" Id="$(PostBuildStepId)" Status="Failed" Condition=" '$(IsDesktopBuild)' != 'true' " />
        </Target>

With that in place, you will see exactly which task failed. As a bonus, it will also give you the time at which it completed. This will easily allow you to compare with your other task to see which one is taking the most time.

I would like to thank Martin Woodward which is a TeamSystem MVP. The question originated from Stackoverflow and more details are also available on Martin's website.


Categories: build | code snippet | tfs
Permalink | Comments (0) | Post RSSRSS comment feed

Why should I use mocking objects in my Unit Test?

If we cut out any "fanboy" or favouritism toward certain framework and that we try to keep it in a one liner... I would say: "To simulate behaviours of objects that are impractical or impossible to incorporate inside a unit test".

The Wikipedia's article about Mock Object mention some reason an object should be mocked.

The object...

Supplies Non-Deterministic Results

By "non-deterministic" we mean everything from time, currency rate, shipping rate, etc. Any value that could be changing because of a specific implementation such as algorithm should be mocked. Mocked object allows you to return predetermined value that are independent of the algorithm/time/etc.

This allows to more easily test the state of the System Under Test (SUT) after running some methods.

Has States that are difficult to create or reproduce

The example given by Wikipedia is "network error". It's difficult to reproduce this kind of situation on every developers station. Other situation might include security, location of the test on disk, network availability (not just errors). If some objects that the SUT is using require any of those, the tests WILL fail somewhere and somehow. If it's not on a developer's machine, it's going to be on the build machine.

Mocking those objects and giving them proper behaviour will remove any required "settings" that are necessary to run a Unit Test.

Is Slow

Databases, network, file access (up to a point) are all slow. If your SUT is an ObjectService that is using a Repository and you are hitting directly on the databases, it is bound to be slow. Of course the database can cope with it. But as you had more tests, the unit will soon take HOURS to run. With a small in-memory database will save the day and run those tests in less than a few minutes.

A mocked repository might just keep a collection of saved object so that when a "Get" method is called, it's readily available in this collection. This kind of mock is called a "fake" in the world of Mocking. It implements more complex behaviour but allows for easy initialization and more timely responses.

Does not yet exist or may change behaviour

If the only thing that is currently available within your system boundaries are contracts (Interfaces in C#), it's more easy to mock the interface that the SUT is requiring and go with this temporarily while the component is being developed. This allow testing and coding at the same time.

Conclusion

Mocking is an excellent tool to test a specific object under controlled conditions. Of course, those conditions are bound to change and tests are going to be maintained. Why I particularly like is when I use a mocking framework, I don't need to create 1000+ objects (exaggerating here) with some specific behaviours or create "too intelligent" mock that will have to be maintained. I dynamically declare a mock with my favourite mocking framework with the expected call and the expected returns and I go through with that.

What normally happens is I have considerably less mocking objects inside my Unit Tests and the only objects that are left standing are some in-memory database objects with simple implementation that would be to hard to define with a mocking framework.


Categories: architecture | mock | opinion
Permalink | Comments (0) | Post RSSRSS comment feed

Is blogging making people blog?

I have a colleague that have his own blog. When I started blogging, it was because of Jeff Atwood's post about starting to write and him having say on StackOverflow's podcast that he's not always right but that he have an online presence and that he's loud.

I agree. Having a blog and writing it (useful or not) is a way to broadcast yourself. Having a blog (depending on what you it) can be good for your career and can also serve as a way to store your personal knowledge that you gained through out projects.

I'm happy that I started my blog. It's kind of a technical diary and I'm more than happy to write to it when I have a moment.

To go back to my colleague, he's a nice guy with a huge technical knowledge. What I'm proud of is this. I started my blog in 2009 and he had his since 2007. During 2007 and 2008 he wrote an average of 5-8 post per years. When I started my blog, he followed me on my journey and we started comparing Google Analytics total number of visits. That's when the friendly competition started.

He knew that I would win easily if he wasn't going to post something interesting. So he started following me. That's why I say that blogging is contagious.

Now instead of making around 8 blog post a year, he makes 8+ a month.

Is that THAT contagious or are we the only duo of blogger like that?


Permalink | Comments (0) | Post RSSRSS comment feed