“Testable Object” pattern

Here’s an interesting article on what the author refers to as the “Testable Object” pattern.

http://bradwilson.typepad.com/blog/2011/06/the-testable-object-pattern.html

Advertisements

MVP vs. MVC Patterns

I recently read an article that mentioned the Model View Presenter MVP pattern.  This was the first time I’ve seen a reference to this pattern and was curious how it was different than the Model View Controller MVC pattern.  The article below offers a great explanation of the two as well as the differences.

http://blogs.infragistics.com/blogs/todd_snyder/archive/2007/10/17/mvc-or-mvp-pattern-whats-the-difference.aspx

Here’s the MVP pattern:

And the MVC Pattern:

Key Differences

So what really are the differences between the MVC and MVP pattern. Actually there are not a whole lot of differences between them. Both patterns focus on separating responsibility across multi components and promote loosely coupling the UI (View) from the business layer (Model).  The major differences are how the pattern is implemented and in some advanced scenarios you need both presenters and controllers.

Here are the key differences between the patterns:

  • MVP Pattern
    • View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
    • Easier to unit test because interaction with the view is through an interface
    • Usually view to presenter map one to one. Complex views may have multi presenters.
  • MVC Pattern
    • Controller are based on behaviors and can be shared across views
    • Can be responsible for determining which view to display (Front Controller Pattern)

Hopefully you found this post interesting and it helped clarify the differences between the MVC and MVP pattern. If not, do not be discouraged patterns are powerful tools that can be hard to use sometimes. One thing to remember is that a pattern is a blue print and not an out of the box solutions. Developers should use them as a guide and modify the implementation according to their problem domain.

Why Interfaces are Important

“The key to understanding interfaces might be to compare them with classes. Classes are objects that have properties and methods that act on those properties. While classes do exhibit some behavioral characteristics (methods), classes are things as opposed to behaviors, and that’s how interfaces come in. Interfaces enable you to define behavioral characteristics, or abilities, and apply those behaviors to classes irrespective of the class hierarchy. For example, say that you have a distribution application in which some of the entities can be serialized. These might include the Customer, Supplier and Invoice classes. Some other classes, such as MaintenanceView and Document,might not be defined as serializable. How would you make only the classes you choose serializable? One obvious way would be to create a base class called something like Serializable. However, that approach has a major drawback. A single inheritance path won’t work because we don’t want all the behaviors of the class to be shared. C# doesn’t support multiple inheritance, so there’s no way to have a given class selectively derive from multiple classes. The answer is interfaces. Interfaces give you the ability to define a set of semantically related methods and properties that selected classes can implement regardless of the class hierarchy.

From a conceptual standpoint, interfaces are contracts between two disparate pieces of code. That is, once an interface is defined and a class is defined as implementing that interface, clients of the class are guaranteed that the class has implemented all methods defined in the interface.”

– C# Interfaces – http://www.brainbell.com/tutors/C_Sharp/Interfaces_a3.htm

SOLID Programming Principles

SOLID programming is a collection of five programming patterns for object-oriented programming and design.  The definition of each of the principles is shown below.

S – Single Responsibility Principle (SRP) – A class should have one, and only one, reason to change.

O – Open/Closed Principle (OSP) – You should be able to extend an classes behavior without modifying it.

L – Liskov Substitution Principle (LSP) – Derived classes must be substitutable for their base classes.

I – Interface Segregation Principle (ISP) – Make fine grained interfaces that are client specific.

D – Dependency Inversion Principle (DIP) – Depend on abstractions, not on concretions.

Single Responsibility Principle (SRP)

This principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class.   All its services should be narrowly aligned with that responsibility.

As an example, consider a module that compiles and prints a report. Such a module can be changed for two reasons. First, the content of the report can change. Second, the format of the report can change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.

The reason it is important to keep a class focused on a single concern is that it makes the class more robust. Continuing with the foregoing example, if there is a change to the report compilation process, there is greater danger that the printing code will break if it is part of the same class.

Open/Closed Principle (OCP)

This principle states “software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.” When a single change to a program results in a cascade of changes to dependent modules, that program exhibits the undesirable attributes that we have come to associate with “bad” design.  The program becomes fragile, rigid, unpredictable and unreusable. The open/closed principle attacks this in a very straightforward way.  It says that you should design modules that never change.  When requirements change, you extend the behavior of such modules by adding new code, not by changing old code that already works.

The simplest way to apply OCP is to implement the new functionality on new derived (sub)classes that inherit the original class implementation. Another way is to mediate client access to the original class with an abstract interface, so new functionality can be implemented on new classes that are accessed through the same interface. Both ways create new classes and leave the original implementation untouched.

Liskov Substitution Principle (LSP)

It states that, in a computer program if S is a subtype of T, then objects of type T may be replaced with objects of type S (i.e., objects of type S may be substitutes for objects of type T), without altering any of the desirable properties of that program (correctness, task performed, etc.)

Here’s an example of a violation of LSP

        void DrawShape(Shape s)
        {
              if (s.GetType() == typeof(Square))
                      DrawSquare((Square) s);
              else if (s.GetType() == typeof(Circle))
                      DrawCircle((Circle) s);
        }

        void DrawSquare(Square s)
        {

        }

        void DrawCircle(Circle s)
        {

        }

The problem with the DrawShape method is that it must know about every possible derivative of the Shape class, and it must be changed whenever new derivatives of Shape are created. Indeed, many view the structure of this function as anathema to Object Oriented Design.

Here’s a better way to implement the method so that it doesn’t have to know all the different types of shapes that need to be drawn.

    class Program
    {
        static void Main(string[] args)
        {
            DrawShape(new Square());
            DrawShape(new Circle());
        }

        static void DrawShape(IShape s)
        {
            s.Draw();
        }
    }

    public interface IShape
    {
        void Draw();
    }

    public class Square : IShape
    {
        public void Draw() { }
    }

    public class Circle : IShape
    {
        public void Draw() { }
    }

Interface Segregation Principle (ISP)

This principle says that once an interface has become too ‘fat’ it needs to be split into smaller and more specific interfaces so that any clients of the interface will only know about the methods that pertain to them. In a nutshell, no client should be forced to depend on methods it does not use.

Here’s an example of an interface used to describe an automobile.

    public interface IAutomobile
    {
        void StartEngine();

        void ApplyBrakes();

        void StopEngine();

        void DropTailGate();

        void EngageFourWheelDrive();
    }

The problem with this interface is that it has a couple of methods that wouldn’t apply to all automobiles. The DropTailGate and EngageFourWheelDrive methods wouldn’t apply to compact cars or minivans, so a new interface would need to be created for each of these with similar methods related to the engine and breaks.

A better design would have seperate interfaces for the specific features that exist for the different types of automobiles.

    public interface IAutomobile
    {
        void StartEngine();

        void ApplyBrakes();

        void StopEngine();
    }

    public interface ISupportsOffRoadDriving
    {
        void EngageFourWheelDrive();
    }

    public interface ITruck
    {
        void DropTailGate();
    }

The interfaces above prevent the duplication of the engine related methods to the other vehicle types and can be applied in addition to the IAutomobile interface.  For example, a class for Truck would implement the ITruck and IAutomobile interface.  If the truck has four wheel drive options, then it would also implement the ISupportsOffRoadDriving interace.

Dependency Inversion Principle (DIP)

The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

The goal of the dependency inversion principle is to decouple high-level components from low-level components such that reuse with different low-level component implementations becomes possible. This is facilitated by the separation of high-level components and low-level components into separate packages/libraries, where interfaces defining the behavior/services required by the high-level component are owned by, and exist within the high-level component’s package. The implementation of the high-level component’s interface by the low level component requires that the low-level component package depend upon the high-level component for compilation, thus inverting the conventional dependency relationship

Here’s an example of a class that will create an automobile. The Automobile class has a dependency on the Engine class for the TurnIgnitionKey method. The code below is an example of a violation of the DIP principle.

    public class Application
    {
        public void CreateAutomobile()
        {
            var automobile = new Automobile();
        }
    }

    public class Automobile
    {
        Engine _engine;

        public Automobile()
        {
            _engine = new Engine();
        }

        public void TurnIgnitionKey()
        {
            _engine.StartEngine();
        }

    }

    public class Engine
    {
        public void StartEngine()
        {
            // ...
        }

        public void StopEngine()
        {
            // ...
        }
    }

Here’s a better implementation which conforms to the DIJ principle.  All the dependent classes are passed to the constructor of the Automobile class.

    public class Application
    {
        public void CreateAutomobile()
        {
            var automobile = new Automobile(new Engine());
        }
    }

    public class Automobile
    {
        Engine _engine;

        public Automobile(Engine engine)
        {
            _engine = engine;
        }

        public void TurnIgnitionKey()
        {
            _engine.StartEngine();
        }

    }

The example above now enables unit testing with mock objects.  This type of testing isolates testing to specific method behavior.  Any dependencies of the method are mocked which confirms that any test failures are isolated to the specific method being tested and none of it’s dependencies.

Useful links:

http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

http://en.wikipedia.org/wiki/Solid_%28object-oriented_design%29

http://blog.symprise.net/2009/06/open-closed-principle-concerns-about-change-in-software-design/

http://www.oodesign.com/dependency-inversion-principle.html

Abstract Factory Pattern

The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage.

The UML below represents how to implement the AbstractFactory pattern.

Abstract Factory Pattern

Let’s consider an example. We need a factory class that will return different brands of cars that include Ford, Chevrolet, and Dodge. Let’s first start by creating an enumeration for the different brands our factory will support.

    public enum AutomobileBrands
    {
        Ford,
        Chevrolet,
        Dodge
    }

Next, let’s define interfaces for our automobile factories as well as the automobiles themselves. We could add more methods for the auto’s, but for now, only two methods for “Start” and “Stop” will be part of the interface.

    public interface IAutomobileFactory
    {
        Automobile CreateAutomobile();
    }

    public interface IAutomobile
    {
        void Start();

        void Stop();
    }

The factory will return an abstract class that defines the common methods and properties for all automobiles. Let’s define this next. The class will have the ToString method overriden so we can display the brand of the automobile as output later on.

    public abstract class Automobile : IAutomobile
    {
        protected AutomobileBrands BrandName { get; set; }

        public virtual void Start()
        {
            Console.WriteLine(String.Format("The {0} has started.", BrandName));
        }

        public virtual void Stop()
        {
            Console.WriteLine(String.Format("The {0} has stopped.", BrandName));
        }

        public override string ToString()
        {
            return String.Format("This is a {0} automobile.", BrandName);
        }
    }

The BrandName property is defined as protected since it will only be defined in the concrete classes. Now let’s define three concrete classes for each of the brands our factory will support creating. Each will implement the IAutomobile interface defined above. I’ve overridden the Start method on a the Chevrolet and Dodge classes to show specific behavior of those brands of automobiles. There’s a lot more differences, but for now let’s keep it simple by showing only a difference with how they start.

    class Ford : Automobile
    {
        public Ford()
        {
            BrandName = AutomobileBrands.Ford;
        }
    }

    class Chevrolet : Automobile
    {
        public Chevrolet()
        {
            BrandName = AutomobileBrands.Chevrolet;
        }

        public override void Start()
        {
            Console.WriteLine(String.Format("The {0} starts Fast.", BrandName));
        }
    }

    class Dodge : Automobile
    {
        public Dodge()
        {
            BrandName = AutomobileBrands.Dodge;
        }

        public override void Start()
        {
            Console.WriteLine(String.Format("The {0} is slowly starting up.", BrandName));
        }
    }

Now let’s create the factories for each brand. Each factory must implement the IAutomobileFactory interface so the main factory class (see below) can call the CreateAutomobile method. Each factory is marked as internal since we only want the main factory class to interact with these classes.

    internal class FordFactory : IAutomobileFactory
    {
        public  Automobile CreateAutomobile()
        {
            return new Ford();
        }
    }

    internal class ChevroletFactory : IAutomobileFactory
    {
        public Automobile CreateAutomobile()
        {
            return new Chevrolet();
        }
    }

    internal class DodgeFactory : IAutomobileFactory
    {
        public Automobile CreateAutomobile()
        {
            return new Dodge();
        }
    }

Now that we’ve defined a factory for each brand, let’s create a static factory class that will be used for creating all types of automobiles. This class will act as the facade for all automobile factories.

    public static class AutomobileFactory
    {
        public static Automobile CreateAutomobileByBrand(AutomobileBrands brand)
        {
            IAutomobileFactory factory;
            switch (brand)
            {
                case AutomobileBrands.Ford:
                    factory = new FordFactory();
                    break;
                case AutomobileBrands.Chevrolet:
                    factory = new ChevroletFactory();
                    break;
                case AutomobileBrands.Dodge:
                    factory = new DodgeFactory();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(brand.ToString(), brand, "Brand is not a valid automobile brand.");
            }

            return factory.CreateAutomobile();
        }
    }

The factory class above only requires one argument which is used to determine what kind of automobile class to create. Now let’s put all this to test by writing some test code in the Main method of the application.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Ford));
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Chevrolet));
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Dodge));

            IAutomobile ford = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Ford);
            ford.Start();
            ford.Stop();

            IAutomobile chevy = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Chevrolet);
            chevy.Start();
            chevy.Stop();

            IAutomobile dodge = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Dodge);
            dodge.Start();
            dodge.Stop();

            Console.ReadLine();
        }
    }

When the program runs, the output displayed in the console is:

This is a Ford automobile.
This is a Chevrolet automobile.
This is a Dodge automobile.
The Ford has started.
The Ford has stopped.
The Chevrolet starts fast.
The Chevrolet has stopped.
The Dodge is slowly starting up.
The Dodge has stopped.

Here’s all of it put together:


using System;

namespace AbstractFactoryExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Ford));
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Chevrolet));
            Console.WriteLine(AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Dodge));

            IAutomobile ford = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Ford);
            ford.Start();
            ford.Stop();

            IAutomobile chevy = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Chevrolet);
            chevy.Start();
            chevy.Stop();

            IAutomobile dodge = AutomobileFactory.CreateAutomobileByBrand(AutomobileBrands.Dodge);
            dodge.Start();
            dodge.Stop();

            Console.ReadLine();
        }
    }

    public static class AutomobileFactory
    {
        public static Automobile CreateAutomobileByBrand(AutomobileBrands brand)
        {
            IAutomobileFactory factory;
            switch (brand)
            {
                case AutomobileBrands.Ford:
                    factory = new FordFactory();
                    break;
                case AutomobileBrands.Chevrolet:
                    factory = new ChevroletFactory();
                    break;
                case AutomobileBrands.Dodge:
                    factory = new DodgeFactory();
                    break;
                default:
                    throw new ArgumentOutOfRangeException(brand.ToString(), brand, "Brand is not a valid automobile brand.");
            }

            return factory.CreateAutomobile();
        }
    }

    #region Interfaces & Enum
    public enum AutomobileBrands
    {
        Ford,
        Chevrolet,
        Dodge
    }

    public interface IAutomobileFactory
    {
        Automobile CreateAutomobile();
    }

    public interface IAutomobile
    {
        void Start();

        void Stop();
    }
    #endregion

    public abstract class Automobile : IAutomobile
    {
        protected AutomobileBrands BrandName { get; set; }

        public virtual void Start()
        {
            Console.WriteLine(String.Format("The {0} has started.", BrandName));
        }

        public virtual void Stop()
        {
            Console.WriteLine(String.Format("The {0} has stopped.", BrandName));
        }

        public override string ToString()
        {
            return String.Format("This is a {0} automobile.", BrandName);
        }
    }

    #region Concrete Autos
    class Ford : Automobile
    {
        public Ford()
        {
            BrandName = AutomobileBrands.Ford;
        }
    }

    class Chevrolet : Automobile
    {
        public Chevrolet()
        {
            BrandName = AutomobileBrands.Chevrolet;
        }

        public override void Start()
        {
            Console.WriteLine(String.Format("The {0} starts Fast.", BrandName));
        }
    }

    class Dodge : Automobile
    {
        public Dodge()
        {
            BrandName = AutomobileBrands.Dodge;
        }

        public override void Start()
        {
            Console.WriteLine(String.Format("The {0} is slowly starting up.", BrandName));
        }
    }
    #endregion

    #region Concrete Auto Factories
    internal class FordFactory : IAutomobileFactory
    {
        public  Automobile CreateAutomobile()
        {
            return new Ford();
        }
    }

    internal class ChevroletFactory : IAutomobileFactory
    {
        public Automobile CreateAutomobile()
        {
            return new Chevrolet();
        }
    }

    internal class DodgeFactory : IAutomobileFactory
    {
        public Automobile CreateAutomobile()
        {
            return new Dodge();
        }
    }
    #endregion
}

Here’s some additional resources to find information about the Abstract Factory pattern.

http://en.wikipedia.org/wiki/Abstract_factory_pattern

http://www.developer.com/design/article.php/626001/Pattern-Summaries-Abstract-Factory-Pattern.htm

http://www.dofactory.com/Patterns/PatternAbstract.aspx