Development

SOLID Development Slides + Code

Solid Development @SlideShare.net

You can download the code for Visual Studio 2010 Beta 2 zipped up and ready to go here.

Too Much of a Good Thing? Constructor Injection Overload

This week there have been two posts covering dependency inversion and going too far with constructor injection.  In the first post Robert C Martin (Uncle Bob) cautions against littering your code with calls to your IoC container. 

I think these frameworks are great tools. But I also think you should carefully restrict how and where you use them.

The post goes on to discuss how to keep the code which builds dependencies contained in one place so that you are not littering your code with calls to the container framework or coupling yourself to other classes using new() statements.

The second post by Jeffrey Palmero takes this a little further and is the one that really got me thinking.  Palmero sets up an example where a class requires two interface dependencies in its constructor.  However, in the code, both dependencies are not always used.  This was a key thing to note, because Palmero’s point was,

The anti-pattern is that one of these constructor arguments is really not a class dependency.

In his example, one of the interface dependencies required in the constructor is only used in some cases.  This was a huge “duh” for me because I know there are several times when I have required everything the class might use in the constructor. 

I think the key here is balance.  Require the real dependencies up front, but also allow for other dependencies to be resolved by blending the use of a container with a factory type pattern.  Keep all the dirty details of your dependent objects and how they are resolved hidden and encapsulated in one place.  This would allow you to switch containers or stop using one all together.

** Update **

A couple readers have posted comments and I would love to hear more.  Be sure to give them a read!

Using a Container To Make a Better Factory

Lately I have been delegating a lot to containers.  If you consider what containers can provide, there are a lot of ways you can leverage them.  Let’s consider the case where you have a Factory implemented using a traditional Factory Pattern to create concrete instances of an abstract type like an interface or base class.

The most common use of the factory pattern involves a switch statement where you say something like “Switch key Case A return new TypeA()”.  Factories are a great way to defer object creation but part of the problem with a factory is that it is very much coupled to the objects it creates and the values used to determine which object to create.  This can be considered as acceptable since you know the factory has a dirty job.  However, let’s consider how we can eliminate the need for switch statements in a factory and let the container do the work.

Most containers support adding objects with a name or key; commonly referred to as a named instance.  This behavior is what we will leverage to make a “better factory.”

Consider this traditional factory (Figure 1)

    public class WidgetRepositoryFactory
    {
        public IWidgetRepository Create(string repositoryKey)
        {
            switch (repositoryKey.ToLower())
            {
                case "xml" :
                    return new WidgetXmlRepository();
                case "csv":
                    return new WidgetFileRepository();
                default :                     throw new ArgumentException("Invalid repositoryKey");
            }
        }
    }

Nothing fancy.  Our traditional factory can provide either an Xml Repository or File Repository.  The repositoryKey could come from a configuration value or even a parameter to some type of request or user input.

Now let’s take a look at a “better factory”.  This example will use StructureMap as the container of choice. 

Note: What this example doesn’t illustrate is how our container bootstraps the application.  To focus on the better factory concept just assume a valid container is populated and provided to the factory when needed. 

Consider our better factory (Figure 2)

    public class WidgetRepositoryBetterFactory
    {
        private readonly IContainerProvider _containerProvider;

        public WidgetRepositoryBetterFactory(IContainerProvider                containerProvider)
        {
            _containerProvider = containerProvider;
        }

        public IWidgetRepository Create(string repositoryKey)
        {
            return (IWidgetRepository)
                _containerProvider.Resolve                   <IWidgetRepository>(repositoryKey);
        }
    }

Within the Create method we are simply using our container to resolve an instance of the IWidgetRepository by it’s key.  This is a bare bones implementation and is not providing any sanity check on the arguments.  There are a couple ways you could go about that, so I’ll leave it up to your imagination.

The “better factory” is wired up to take an instance of an IContainerProvider which looks like the following:

    public interface IContainerProvider
    {
        object Resolve<T>();
        object Resolve<T>(string key);
    }

We can wire this up in Structure Map like so:

      public StructureMapProvider()
        {
            _container = new Container();
            _container.Configure(x =>
            {
                x.ForRequestedType<IContainerProvider>()                  .TheDefault.IsThis(this);
                x.ForRequestedType<IWidgetRepository>().AddInstances
                    (i => i.OfConcreteType<WidgetFileRepository>()                         .WithName("csv"));
                x.ForRequestedType<IWidgetRepository>().AddInstances
                    (i => i.OfConcreteType<WidgetXmlRepository>()                         .WithName("xml"));
            });
        }

When someone calls our StructureMapProvider’s Resolve<T> method for IContainerProvider, they will be given that instance of the StructureMapProvider.  This can be a little confusing at first, but in cases where you do not want your container to be created multiple times, this allows you to to set up your container to support that.

The important lines to review in the StructureMap configuration are these two:

x.ForRequestedType<IWidgetRepository>().AddInstances
   (i => i.OfConcreteType<WidgetFileRepository>().WithName("csv"));
x.ForRequestedType<IWidgetRepository>().AddInstances
   (i => i.OfConcreteType<WidgetXmlRepository>().WithName("xml"));

As of StructureMap 2.5.2 this is how you can register named instances within the Configure expression.  What I think is a little misleading is that this sounds as though you are creating this as a Singleton by saying “Add an instance of this type, with this name.”  In my testing I found that the instance returned when resolving one of these types is a new instance.  The grammar of the API can be a bit tricky if you are not fully-versed in it.

Containers certainly offer a lot of power and you can delegate a lot to a container.  Hopefully next time you need to leverage a factory you can consider how to make it a “better factory”™.  Enjoy!

Loving Linq & Generics: Using .Except with EqualityComparer<T>

In the last post on Loving Linq we covered the .Except method for comparing two lists.  The example was very simple and demonstrated how to compare to String lists.  In this post we’ll cover an advanced scenario where we need to compare lists of a class we created.

We’ll start with an implementation of IEqualityComparer<T> EqualityComparer<T> which consists of overriding two methods: Equals and GetHashCode.  What was a little tricky about this implementation is this subtle, but critical, comment in the code sample on MSDN (in the Enumerable.Except documentation):

// If Equals() returns true for a pair of objects,
// GetHashCode must return the same value for these objects.

    public class WidgetComparer : EqualityComparer<Widget>
    {
        public override bool Equals(Widget x, Widget y)
        {
            if (ReferenceEquals(x, y)) return true;

            return x.Id == y.Id && x.Name == y.Name && x.Price == y.Price;
        }

        public override int GetHashCode(Widget obj)
        {
            if (ReferenceEquals(obj, null)) return 0;

            var nameHash = obj.Name == null ? 0 : obj.Name.GetHashCode();
            var idHash = obj.Id.GetHashCode();
            var priceHash = obj.Price.GetHashCode();

            return nameHash ^ idHash ^ priceHash;
        }
    }

Now that we have our EqualityComparer set up for the Widget class, let’s look at how the Except method uses our implementation.

Test 1 – Two lists with same reference items.

 [TestMethod]
        public void Except_ListsWithSameReferenceItems_ShouldNotYieldDifferences()
        {
            var widget1 = new Widget { Id = 1, Name = "Widget1",                                       Price = 0.99 };
            var widget2 = new Widget { Id = 2, Name = "Widget2",                                        Price = 0.99 };
            var list1 = new List<Widget> { widget1, widget2 };
            var list2 = new List<Widget> { widget1, widget2 };

            var results = list1.Except(list2, new WidgetComparer());

            Assert.IsTrue(results.Count() == 0);
        }

Note in our implementation (which follows the example from MSDN) we check object.ReferenceEquals in the Equals method.  But that check alone will not suffice, the result from GetHashCode is also validated so we must calculate the HashCode uniformly for the object as well.

Test 2 – Two lists with same items (but not same references)

         [TestMethod]
        public void Except_ListsWithSameItems_ShouldNotYieldDifferences()
        {
            var list1 = new List<Widget>
                            {
                                new Widget { Id = 1, Name = "Widget1",                                             Price = 0.99 },
                                new Widget { Id = 2, Name = "Widget2",                                            Price = 0.99 }
                            };
            var list2 = new List<Widget>
                            {
                                new Widget { Id = 1, Name = "Widget1",                                            Price = 0.99 },
                                new Widget { Id = 2, Name = "Widget2",                                            Price = 0.99 }
                            };

            var results = list1.Except(list2, new WidgetComparer());

            Assert.IsTrue(results.Count() == 0);
        }

In this test we use widgets set up with identical properties for each list.  The test will still pass because our EqualityComparer evaluates the widgets using the formula we specified (Id, Name, & Price all match).

Test 3 – Two lists with different items.  This one is tricky though, because it List 2 is the one that contains different items.

          [TestMethod]
      public void Except_List2WithDifferentItems_ShouldNotYieldDifferences()
        {
            var list1 = new List<Widget> {
                new Widget { Id = 1, Name = "Widget1", Price = 0.99 },
                new Widget { Id = 2, Name = "Widget2", Price = 0.99 }
            };
            var list2 = new List<Widget>{
                new Widget {Id = 1, Name = "Widget1", Price = 0.99},
                new Widget {Id = 2, Name = "Widget2", Price = 0.99},
                new Widget { Id = 3, Name = "Widget3", Price = 0.99 }
           };

            var results = list1.Except(list2, new WidgetComparer());

            Assert.IsTrue(results.Count() == 0);
        }

What gives?  When you call Except you are saying “Give me everything that is in list 1, that is not in list 2.”  In this case, list 2 has more items than list 1 and all the items from list 1 are in list 2.

Test 4 – Two lists with different items.  This time list 1 has more items than list 2.

        [TestMethod]
        public void Except_List1WithDifferentItems_ShouldYieldDifferences()
        {
            var list1 = new List<Widget> {
                new Widget { Id = 1, Name = "Widget1", Price = 0.99 },
                new Widget { Id = 2, Name = "Widget2", Price = 0.99 },
                new Widget { Id = 3, Name = "Widget3", Price = 0.99 }
            };
            var list2 = new List<Widget>{
                new Widget {Id = 1, Name = "Widget1", Price = 0.99},
                new Widget {Id = 2, Name = "Widget2", Price = 0.99}
           };

            var results = list1.Except(list2, new WidgetComparer());

            Assert.IsTrue(results.Count() == 1);
        }

image

As expected, we find that Widget3 does not exist in list 2.  Remember, when you call Except, say the mantra: “Give me everything that is in list 1, that is not in list 2.”

If you have any comments or improvements on this simple example of using Except, post away!

Loving Linq: Use .Except to Find the Difference Between Two Lists

While working on a side project for a friend who needed a program to compare two files, I discovered a handy extension method called ‘Except’.  This method allows you to take two lists and find the set difference between the two.  For strings, this was pretty straight-forward and I just followed the example from MSDN.

Example

var differenceQuery = sourceList.Except(externalList);

The result of this query will be an IEnumerable of the type from each list (in this case it was a string).  The list will contain everything from “sourceList” that does not exist in “externalList”.

What do you do if you need to check lists of your own classes?

Just implement an IEqualityComparer<T> for your class.  We’ll cover that in a future post!

image

Making Mockery with Moq

Recently I was able to get into using the Moq framework for testing code.  For a long time I have wanted to dig in and use mocking as a strategy to test code without all the dependencies.  There is a lot of theory and debate on mocking and I suggest you give some of that a read.  Check out Martin Fowler’sMocks aren’t Stubs” or Roy Osherove’sArt of Unit Testing

For today’s example I’m going to focus on using Moq for what most would call a Stub.  Let’s take Moq for a spin.

Listing 1 – For this exercise we’ll be working with a Product class.  Products have a name and price and … that’s  it.

    public class Product
    {
        public string Name { get; set; }
        public double Price { get; set; }
    }

Listing 2 – IProductRepository

    public interface IProductRepository
    {
        IEnumerable<Product> GetProducts();
        Product GetProduct(string name);
        int AddProduct(Product product);
    }

Listing 3 – ProductService AddProduct method.  A little business logic to give us something to test.

     public int AddProduct(Product product)
        {
            if (string.IsNullOrEmpty(product.Name))               { throw new ArgumentNullException("product.Name"); }
            if ((product.Price < .10))               { throw new ArgumentException("product.Price"); }

            return _repository.AddProduct(product);
        }

Listing 4 – The tests rely on a _mockRepository initialized as a new Moq.Mock<IProductRepository> in the tests constructor.

private static Moq.Mock<IProductRepository> _repositoryStub;

Listing 5 – The unit tests are where the magic happens.  In our first test, which should succeed, we are initializing our stub to return the number 5 when add product is called with our Candy Bar product.  When this test executes our product service takes in the product, runs the business rules (name cannot be null and price greater than 10 cents) and calls the repository.  In our test the repository being called is actually our stub, so the product never goes to the database.

In the second test you’ll see that we do not initialize stub at all because the test should throw an exception when we try to add a product with a null name.

        [TestMethod()]
        public void AddProduct_ValidProduct_ShouldAddProduct()
        {
            Product newProduct = new Product("Candy Bar", .75);
            _repositoryStub.Setup
                (repo => repo.AddProduct(newProduct)).Returns(5);

            ProductService target =
                new ProductService(_repositoryStub.Object);
            int actual =
                target.AddProduct(newProduct);

            Assert.IsTrue(actual ==5);
        }

        [TestMethod()]
        [ExpectedException(typeof(ArgumentNullException))]
        public void AddProduct_MissingProductName_ShouldThrowArgumentNullException()
        {
            ProductService target = new ProductService
                (_repositoryStub.Object);

            int actual = target.AddProduct
                (new Product { Name = null, Price = 1.5 });
        }

In the constructor for the ProductService you’ll note that _repositoryStub.Object is passed.  In Moq, the object property of the stub is what holds the actual stub you want to use.

This example just scratches the surface of using a mocking framework.  Mocks are great for testing your code in isolation and there are strategies of how you can effectively do that.

In general I began using stubs to test dependencies between a class and interfaces it talks with to get work done.  The service class example above is a common one I’ll use.  We can test the logic of the service class without needing the repository.  This does not leverage the full power of Moq but should be good enough to get you started down the path of mockery.

Enjoy!

Getting to SOLID

The acronym for SOLID has been making rounds for some time now.  SOLID is a set of principles that will help you write code that is easier to understand, maintain, and simple. 

Writing SOLID code is not easy and takes effort and craftsmanship.  The road to SOLID is not a direct route and you’ll need practice to get there.

Don’t start with SOLID.

Solve the problem first.  When you are first given requirements have a design discussion to outline responsibilities for classes or interfaces based on the requirements but keep the design loose.  Consider SOLID in that design discussion but don’t spend all your time on it.  Think about the requirement and how you’re going to implement it with code.  Once you start coding the code will paint a picture; it’s too hard to paint the picture first.

Getting to SOLID Requires Iterations.

Not project level iterations.  These are much smaller, could be several per day.  As you make your tests pass you gain a better understanding of the solution and you can begin refactoring code.  The other day, in one 15 minute pair programming session, the project architect and I removed about 25+ lines of code.  Shortly there after I performed some major refactoring.  The codes understandability improved and the tests continued to pass.

Find New Eyes

Sometimes you get stuck in how you’re thinking about a problem.  In my pair programming example above the project architect was able to see things differently and helped me get past a hurdle.  If you’re stuck, find a trusted colleague or just put the code away and do something else for a while.  When you come back with new eyes you might be able to simplify the code.

SOLID is a set of Principles

SOLID is not a solution but a set of principles to help get you there.  Keep them in mind and use them judiciously as you refactor new or old code.

Know When to ‘yield’ (C# goodies)

One of the fun things as I have begun working more in C# is that I’m finally able to leverage all those fancy language features that do not have a VB equivalent.  The other day I was reviewing code with the project architect and he caught me using the yield keyword.  He thought it was a good use of yield and we ended up changing several interfaces to return IEnumerable<T> so we could leverage yield and a few other .NET 3.5 features.

When to yield

The yield keyword allows you to build up results within an iterator statement and return a type derived from IEnumerable (or IEnumerable<T>).  In MSDN speak:

Used in an iterator block to provide a value to the enumerator object or to signal the end of iteration.

Let’s take a look at the following code that gets an IEnumerable of Wishlist Items:

        public IEnumerable<WishlistItem> GetAll()
        {
            ///boring database code here
            var i = 0;
            var items = new List<WishlistItem>();
            while (i < 5)
            {
                items.Add(new WishlistItem("Item" + i,
                    "Item" + i + " details",
                    new Uri("http://localhost/item/" + 1)));
                i++;
            }
            return items;

        }

Using yield we can rewrite the same code as follows:

   public IEnumerable<WishlistItem> GetAllWithYield()
        {
            ///boring database code here
            var i = 0;
            while (i < 5)
            {
                yield return new WishlistItem("Item" + i,
                    "Item" + i + " details",
                    new Uri("http://localhost/item/" + 1));
                i++;
            }
        }

Visual Studio/.NET/WCF/LINQ and NIEM Tips

Over the years while working with .NET and NIEM I’ve run into a few kinks that require a setting tweak or an extra step to get it to work. 

.NET General

Choices for working with NIEM Xml (From the .NET Base class library.  There are third-party tools out there to assist as well):

Linq

  • System.Xml.Linq.XDocument, XElement, et. al. are not Serializable.  You cannot accept them as an input or return them as an output from services (Web/Sockets/Queues/etc) or any place that will attempt serialize them.
  • With Linq to Xml using XDocument or XElement changes the axis for your query.  If you parse a string to an XDocument your query starts at the root node.  If you parse a string into XElement your query starts from the first element in the Xml and not at the root.  Typically this isn’t a major hassle but the problem is that you may not notice it until you actually try a query at run time and do not get the results you expect. (See also Unit Testing!)

WCF

  • MaxReceivedMessageSize and MaxStringContentLength will be your enemies.  Every service you write, you will want to change those values from the default 65536 otherwise callers to your service will get a nice Fault Exception when they send you a message larger than that.
  • MaxItemsInObjectGraph will need to be adjusted if you are going to be serializing large objects using direct serialization or you try to return a very large list or array of objects.
  • MaxArrayLength should be adjusted in conjunction with MaxItemsInObjectGraph.  Typically you’ll need to adjust both.  You’ll use arrays more if you do any interop work between .NET and other technology stacks as Arrays are typically safer for Xml serialization.
  • For interop scenarios your best bets are to stay with simple data types supported by Xml Schema (Xsd): String, Date, Integer, and arrays thereof.  Adding specific .NET types like GUID, List<T>, etc will add additional schemas to your service contract and may cause issues with other technology stacks.
  • Data Contract Serialization (the default) gives you less control over your Xml messages.  Xml Serialization gives you fine grain control and is usually a better fit for working with NIEM in WCF.

Visual Studio

  • Visual Studio solutions only allow an Xml Namespace to be defined once.  If you try to import two XSDs that define the same namespace you will not be able to leverage the Xml Intellisense and document validations provided by the Xml parser in Visual studio.  This really comes into play if you attempt to import LEXS digest and payload schemas in the same solution.
  • Typically I would create a project in a VS Solution just for Xml Schemas.  You can use a class library and it is not necessary to reference it from other projects.  Schemas are used at the solution level, even when the schemas are in a project.
  • While navigating an Xml document if you type an opening bracket, select an Xml element, and press tab twice studio will create an Xml fragment with all the required elements.

These are certainly not all the tips, but its a start.  Feel free to contact me if you have some to share or have any questions!

LINQ to NIEM On CodePlex

Following up on the “IEPD Development in the .NET Environment” that I co-presented with Carl Nelson, I have posted the source code to the LINQ to NIEM example on CodePlex at http://linq2niem.codeplex.com/.

Look through the source and shoot me any questions you might have!

There is more NIEM and .NET goodness to come.  Stay tuned!