Patterns for Splitting User Stories

Here’s a helpful link with tips on creating user stories based on the INVEST model (Independent, Negotiable, Valuable, Estimable, Small, and Testable)

http://www.richardlawrence.info/2009/10/28/patterns-for-splitting-user-stories/

 

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

Clean Code Tip – Method Purpose

Methods should either do something or decide something, but not both.

For example, the method below has a method GetDistinctArrarCount that returns an array count and it removes empty elements.  The removal elements should be done separately since the method purpose is to get the array count.

static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Remove Emtpy Values
            arrayValues = arrayValues.Where(x => !String.IsNullOrEmpty(x));

            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }

Here’s a better way to write this:

 static void Main(string[] args)
        {
            List<string>  people = new List<string>() { "Brian", "Sara", "", "Bob"};

            // Remove empty elements before getting the distinct count
            people = people.Where(x => !String.IsNullOrEmpty(x)).ToList();
            int count = GetDistinctArrayCount(people);

            Console.Write(count);
            Console.ReadLine();
        }

        private static int GetDistinctArrayCount(IEnumerable<string> arrayValues)
        {
            // Return Distinct Count
            return arrayValues.Distinct().Count();
        }

DynamicObject

I ran across this the other day when looking at some code from the Internet.  I hadn’t heard of DynamicObject before, so I thought I’d investigate.  The definition from MSDN states that it “Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.”

You can think of it as something similar to the .NET Object class, except that it enables you to define which methods or properties can be performed at run time.

For other classes, you will get a compile time error when you’ve written code against a nonexistent method.  Classes that inherit from DynamicObject will not, but will be instead evaluated at run time.  If the dynamic class hasn’t implemented the method or coded for nonexistent methods, then a run time error will be thrown.

Here’s an example:

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {

    }
}

The MyDynamicClass inherits from DynamicObject and is completely empty.  However, the Main method is calling a method called MyAdder which sonds like it adds two integer arguments.  When this code is compiled, there’s no errors, but when we run we get a “RunTimeBinderException was unhandled error” which states that “‘DynamicObjectExample.MyDynamicClass’ does not contain a definition for ‘MyAdder’.”

To add logic for situations where a method is invoked which doesn’t exist, the TryInvokeMember method can be overridden.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }
    }
}

The result of the above is

“MyAdder Method not present in this class

Result: 0”

with no exceptions.  Now let’s see what happens when we actually implement the MyAdder method on MyDynamicClass.

using System;
using System.Dynamic;

namespace DynamicObjectExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic test = new MyDynamicClass();

            int result = test.MyAdder(1, 2);

            Console.WriteLine("Result: " + result);
            Console.ReadLine();
        }
    }

    class MyDynamicClass : DynamicObject
    {
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            Console.WriteLine(binder.Name + "  Method not present in this  class ");
            result = 0;
            return true;
        }

        public int MyAdder(int x, int y)
        {
            return x + y;
        }
    }
}

The result of the above will be “Result: 3” which is what we expect :).

TryGetMember and TrySetMember are other virtual members on DynamicClass that allow you to add logic for getting and setting properties that do not exist.

How Facebook Ships Code (via FrameThink – Frameworks for Thinking People)

I’m fascinated by the way Facebook operates.  It’s a very unique environment, not easily replicated (nor would their system work for all companies, even if they tried).  These are notes gathered from talking with many friends at Facebook about how the company develops and releases software. It’s been over six months since I assembled these observations and I’m sure Facebook has continuously evolved its software development practices in the meanti … Read More

via FrameThink – Frameworks for Thinking People

Clean Code Tips: Method Arguments

Methods should have as few arguments as possible. Ideally, they should never have more than three.  If there’s more than three, then it’s likely the arguments should be wrapped into a class of their own.

Boolean arguments should be avoided because it complicates the method name and the purpose of the method. Passing a boolean will likely cause your method to do two different things based on the bool.  This is in contradiction to a previous rule.

Methods that change input arguments should be defined so the argument is the return value. This also prevents the usage of output arguments which can be confusing.

Clean Code Tips: Methods

Methods should be small.  Ideally, they should hardly ever be 20 lines long.  This forces the developer to create more methods that can shared and tested more easily.  Smaller methods will also result in less unit tests for each method since there’s less logic applied.

Keeping method small also helps to enforce the concept that methods should only do one thing.  The more logic that exists in a method will likely limit it’s ability to be shared and reused.  It also ensures that changes to the method will only affect the single purpose of the method.

One level of abstraction per method is also a good rule to follow.  This helps others understand what the method is doing which prevents bugs from getting into the software.

Following the above tips will result in more methods, but it doesn’t necessarily result in more code since methods can be shared more easily.