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

Back to basics: Why should I use interfaces?

So I had this interesting discussion with a colleague about having a clean architecture for a small software he is doing. Since it's his first step among SOLID, I wanted to take it easy see how things were laid out. Since the program was mostly already written, I immediately noticed the lack of pattern and the direct data access in the event of his WinForm application. The conversation went a bit like this:

Me: What is this code with data access on the "OnClick" of your button? Him: Well it's the information I need to execute this command. Me: Do you know the Model-View-Presenter pattern? Because right now, you are mixing "Presentation", "Data Access" and "Business Logic" Him: I've used it before but it's been a while. How do you implement it?

So after showing him the pattern and explaining the basic implementation (because there is a lot of different way to implement this pattern), he asked me the following question:

"Of course, you don't need to use interface everywhere, right?"

But then I went on to explain testability and such but there is something different I wanted to bring to this small discussion and that I wanted to share a bit. When my class have dependencies injected through the constructor, I have 2 choices. Either I depend upon the implementation or the abstraction (interface/abstract). What's the difference and why is it so important?

MyClass depending upon the abstraction of "MyClassDataAccess"

When your class depend upon the abstraction, it can take any class that implement that abstraction (be it abstract class or interface). The implementation can easily be replaced by something else and that is essential in unit testing your logic.

MyClass depending upon the implementation of "MyClassDataAccess"

When your class depend upon the implementation directly, the only that can be sent to this class is this specific implementation. Anything else must derive from this class. This implementation couple the Caller and the Callee really tightly.

Why is it important ?

When you have a class that access services, slow resource (database, disk, etc.) or even a class that you haven't coded yet... an interface should be used. Of course it's not a law. You apply interface/abstract class when you need to decouple an implementation of a system from another system. That allows me to send mocked object and test my requirements/logic. This also bring another advantage that might not be evident at first. Customer changing his mind. When the customer change his mind and do not want to store information in an XML but instead want a database. Or when a customer say to not implement "this part of the system" because it will be available through a service. Etc Etc... Using interfaces and abstract class is the oil that makes the engine of your software turn smoothly and allow you to replace parts by better/different parts without hell breaking loose because of tightly coupled implementation.


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

Simple explication of the MVC Pattern

Since the last time I wrote a blog post was more than a few months ago, I would like to start by saying that I'm still alive and well. I had changes in my career and my personal life that required some attention and now I'm back on track.

So for those that know me, I was participating to the TechDays 2009 in Montreal and presenting the "Introduction to ASP.NET MVC" session. I will also be presenting the same session in Ottawa (in fact this blog post is written on the way to Ottawa with Eric as my designated driver).

So what is exactly ASP.NET MVC? It's simply the Microsoft's implementation of the MVC pattern that was first described in 1979 by Trygve Reenskaug (see Model-View-Controller for the full history).

So in more details, the MVC is the acronym of Model, View and Controller. We will see each component and the advantages of having them separated properly.

Model

The model is exactly what you would expect. It's your business logic, your data access layer and whatever else is part of your application logic. This I don't really have to explain. It's where your business logic will sit and therefore should be the most tested part of your application.

The model is not aware of the view or of the controller.

View

The view is where sit your presentation layer for your application. In a web framework, this is mostly ASPX pages with logic that is limited to showing the model. This layer is normally really thin and only focused on displaying the model. The logics are mostly limited to encoding, localization, looping (for grids) and such.

The view is not aware of which controller invokes it. The view is only aware of the model to display.

Controller

The controller is the coordinator. It will retrieve data from the model and hand it over to the view to display. The controller can also be associated to other cross-cutting concerns such as logging, authorization and performance monitoring (performance counter, timing each operations, etc.).

Advantages

Now, why should you have to care about all that? First, there is a clear cutting separation between WHAT is displayed to the user and HOW you get the information to display. In the example of a web site, it become clearly possible to display different views based on the browser, the device, the capabilities of the device (javascript, css, etc...) and any other information available to you at the moment.

Among the other advantages, it's the ability to test your controller separated from your view. If your model is properly done too (coding against abstraction and not implementations), you will be able to test your controller separated from your model and your view.

Disadvantages

Mostly a web pattern than a WinForm pattern. There is currently no serious implementation of the MVC pattern for anything else other than web frameworks. The MVC pattern is hence found in ASP.NET MVC, FubuMVC and other MVC Framework. Thus it limits your choices to the web.

If you take a specific platform like ASP.NET MVC, other disadvantages (that could be seen as advantages) slips in. Mostly, you lose any drag and drop support for server controls. Any grids are now required to be hand-rolled and built manually instead the more usual abstraction offered by the original framework.

Conclusions

Since we mostly require to have a more fine grained control over our view, the abstraction offered by the core .NET Framework are normally not extensible/customizable enough for most web designers. Some abstraction might even become unsupported in the future and thus bringing us to a more precise control of our views. The pattern also allow us greater testability than what is normally offered by default in WebForms (Page Controller with Templating Views).

My recommendation will effectively be a "it depend". If an application is already built with WebForms and doesn't have any friction, there is no point in redoing the application completely in MVC. However, for any new greenfield project, I would recommend at least taking a look at ASP.NET MVC.


Categories: architecture | asp.net | mvc | pattern
Permalink | Comments (0) | Post RSSRSS comment feed

My baby steps to PostSharp 1.0

So... you downloaded PostSharp 1.0 and you installed it and are wondering... "What's next?".

Well my friends, let me walk you through the first steps of PostSharp. What could we do that would be simple enough? Hummm... what about writing to a debug window? That sounds simple enough! Let's start. So I created a new Console Application project and I added the reference to PostSharp.Laos and PostSharp.Public. As a requirement, the class must be tagged with "Serializable" attribute and implement OnMethodBoundaryAspect (not in all case but let's start small here).

Next, I have a few methods I can override. The two that we are interested in right now is "OnEnter" and "OnExit". Inside of it, we'll say which method we are entering and which one we are exiting. Here are my Guinea pig classes:

public class FooBar
        {
        [DebugTracer]
        public void DoFoo()
        {
        Debug.WriteLine("Doing Foo");
        }

        [DebugTracer]
        public void DoBar()
        {
        Debug.WriteLine("Doing Bar");
        }
        }

        [Serializable]
        [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
        public class DebugTracer : OnMethodBoundaryAspect
        {
        public override void OnEntry(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Entering {0}", eventArgs.Method.Name));
        }

        public override void OnExit(MethodExecutionEventArgs eventArgs)
        {
        Debug.WriteLine(string.Format("Exiting {0}", eventArgs.Method.Name));
        }
        }

See how simple this is? But... does it work? Let's see the trace of calling each methods:

Entering DoFoo
Doing Foo
Exiting DoFoo
Entering DoBar
Doing Bar
Exiting DoBar

Isn't that wonderful? Compile execute and enjoy. But... what about the community you say? Of course if the tool is not open source there is probably nothing built around it, right? Wrong!

Here is a few resources for PostSharp that include pre-made attributes that are ready to be used:

That was everything I could find. Do you know any others?


Permalink | Comments (0) | Post RSSRSS comment feed

Implementing a Chain-of-responsibility or "Pipeline" in C#

Anti-Patterns are interesting in showing you what you are doing wrong. However, patterns are also interesting in showing you how to do it well.

This time, I want to show how to implement a simple Chain-of-responsibility pattern. Our example is going to be based on a simple e-Commerce data model.

The Domain Model

Product which will have some basic attributes like a price, a name and a collection of applied discounts.

Discount which is going to be an actual discount implementation. More class are going to be derived from this base class.

That is all we are going to need for this pattern. However, it would be smart to have a class that would assign discounts to product based on certain rules.

Let's start by writing our Product class and our Discount interface:

public class Product
        {
        private readonly List<IDiscount> _appliedDiscount = new List<IDiscount>();

        public string ProductName { get; private set; }
        public decimal OriginalPrice { get; private set; }

        public decimal DiscountedPrice
        {
        get
        {
        decimal discountedPrice = OriginalPrice;
        return discountedPrice;
        }

        }

        public Product(string productName, decimal productPrice)
        {
        ProductName = productName;
        OriginalPrice = productPrice;
        }

        public List<IDiscount> AppliedDiscount
        {
        get
        {
        return _appliedDiscount;
        }
        }
        }

        public interface IDiscount
        {
        decimal ApplyDiscount(decimal productPrice);
        }

Right now, the "DiscountedPrice" is simply returning our "OriginalPrice". Let's implement the proper discount commands:

public decimal DiscountedPrice
        {
        get
        {
        decimal discountedPrice = OriginalPrice;

        foreach (IDiscount discount in _appliedDiscount)
        discountedPrice = discount.ApplyDiscount(discountedPrice);

        return discountedPrice;
        }
        }

Now that we have an algorithm that will apply all discounts, let's create a few Discount class:

public class PercentageDiscount : IDiscount
        {
        public decimal PercentDiscount { get; set; }

        public PercentageDiscount(decimal percentDiscount)
        {
        PercentDiscount = percentDiscount;
        }

        public decimal ApplyDiscount(decimal productPrice)
        {
        return productPrice - (productPrice*PercentDiscount);
        }
        }

        public class FixPriceDiscount : IDiscount
        {
        public decimal PriceDiscount { get; set; }

        public FixPriceDiscount(decimal priceDiscount)
        {
        PriceDiscount = priceDiscount;
        }

        public decimal ApplyDiscount(decimal productPrice)
        {
        return productPrice - PriceDiscount;
        }
        }

So now we have a class that implement a percentage discount and another one that impose a fixed rate discount. Of course, our current implementation should NEVER be used in a real system as it is now. Validations must be done for a positive price and maybe some extra verification that we are not underselling the item.

Let's use this current implementation:

// Creating a product worth 50$
        Product currentProduct = new Product("Simple product", 50.0M);

        Console.WriteLine(string.Format("Original Price: {0}", currentProduct.OriginalPrice));

        // Give a 10% rebate on the product
        currentProduct.AppliedDiscount.Add(new PercentageDiscount(0.1M));
        Console.WriteLine(string.Format("Discounted Price: {0}", currentProduct.DiscountedPrice));

        //Give an extra 10$ off on the product
        currentProduct.AppliedDiscount.Add(new FixPriceDiscount(10.0M));
        Console.WriteLine(string.Format("Discounted Price: {0}", currentProduct.DiscountedPrice));

This will output in order 45.00$ and 35.00$.  It's important to be aware that the discount interfaces are not aware that they are being applied to a product. They could be reused in any other model that accepts an IDiscount.

Conclusion

By chaining Strategy Pattern (the discount algorithms), we can increase the amount of flexibility inside our model and increase the reuse of common algorithms. It would also be easy with a simple rule engine to apply discounts to product that match certain rules.

Other uses of a chain-of-responsibility could be when dealing with objects that could have multiple rules applied to them based on different conditions. The conditions would then be moved from the object itself to a "Command" and then reused exactly the same way we did here.


Categories: architecture | c# | pattern
Permalink | Comments (0) | 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

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