Saturday, May 29, 2010

Azure In Action Book Review

This week I just finished co hosting the Minneapolis Windows Azure boot camp.  We had about 100 folks show up which near as I can tell makes it one of the largest if not the largest boot camp in the country. By way of preparation for the event Manning Publishing, Chris Hay, and Brian Prince were kind enough to provide me with a copy of Azure in Action.  Being a consultant at Intertech here in Minneapolis, I pretty much always have a full time customer that pays me to do work (for them of course).  When I am trying to learn a new subject I tend to do it off hours and I tend to only have small half hour time slices to really focus on it.  I need a book that I can pick up for a short period of time 4 or 5 times a week and if I skip a couple days I don’t want to have to struggle with trying to remember where I left off.   Azure In Action fit the bill perfectly. 

Chris Hay and Brian Prince (Manning Publications) do an excellent job of sprinkling in a refreshing dose of IT humor as they show us how to use this exciting new platform and teach us how we need to think differently about how we architect an application for the clouds.  Chapter 11 section 1 has a perfect example of this combination of humor and new way of thinking about architecture:


Surely I always need a relational database, you pillock?
Over the past decade or so, there has been a government conspiracy to make us always use relational databases to track our data ;). Every database vendor has some secret code in their product that means the government can query our data whenever they want.
Okay, so the above statement is a bunch of baloney but there is a serious point there (no really there is). We are a little conditioned to store our data in a relational form, even when it's not strictly necessary.
If you can expand your mind and except that there are other ways of storing data then you can use the Table Service to store your data in a highly scalable (and cheaper fashion).”

If you are thinking about using the Windows Azure platform or just getting started on an Azure project, do yourself a favor and go out and get a copy of Azure in Action – you won’t regret it.


Friday, March 5, 2010

Friday, February 5, 2010

Not moving just yet

I am having some technical difficulties getting images posted to my new blog site so I’ll revise my statement.  Very soon I will be blogging on an internally managed blog site at Intertech (  I will not be moving existing content but I will continue to update the links on my design and code review check list until it is complete.

Consider composition over inheritance

This week I want to discuss another bullet from my code review checklist.

Composition is a method we use to combine simple objects into more complex objects.  With composition we have an owner class that changes behavior by delegating the implementation of certain behaviors to smaller and simpler objects.  When we destroy the owner object, all of these smaller objects the owner uses are also destroyed.  If we were to use inheritance to achieve this same goal (changing behavior) we would use a subclass to change the behavior of the base class.  As I mentioned in my last post,  the base class and subclass are tightly coupled and this can tend to be a bit brittle.  

Consider the very real case where we are writing an application that needs to work with both Oracle and SQL Server.  We could use inheritance to define a base class and have one subclass for SQL Server and another for Oracle.  Our application can figure out which object to instantiate at runtime and that will work pretty well. Here is what our class diagram might look like:


If we take a little different approach and use composition instead we might have a class diagram similar to the following.


The CompositionDatabaseWriter does not need to implement IDatabaseWriter but I did that because I think it makes the example easier to understand.  The application will use the CompositionDatabaseWriter to do database work and CompositionDatabaseWriter will determine whether to use SqlServerDatabaseWriter or OracleDatabaseWriter at runtime perhaps by using a configuration file entry.  When one of the CompositionDatabaseWriter methods is called, CompositionDatabaseWriter simply calls the corresponding method on the Sql Server or Oracle object. 

Both designs allow us to interact with an oracle or Sql Server database which was our goal.  Now here is where the flexibility of composition comes in;  Suppose we now need to support a MySql database.  If we use inheritance to solve this problem, at a minimum we must create a MySqlDatabaseWriter subclass, recompile, test, and deploy our data layer.  If we use composition instead we can create a MySqlDatabaseWriter in a new assembly and all we have to do to use it is deploy this single assembly and change a config file.  Very powerful, because we used composition we can change the behavior at runtime via configuration.

The fact of the mater is that our sample is so simple we didn’t even use composition at all so imagine the considerably more complex scenario where what we are doing is creating a persistence object that must transactionally work with the file system and a database.  We define the persistence object and within the persistence object we delegate the responsibility of dealing with the file system to one class, and dealing with the database to another.  The persistence object is composed of a FileSytemWriter and a DatabaseWriter.  Our Persistence object has only one concern – coordinating database and file persistence.  Our FileSystemWriter has only one concern – managing File System interactions, and finally our DatabaseWriter is only concerned about interacting with a database of one type.  We have decomposed a fairly complex problem into a few smaller more managable problems, we came up with a nice robust design thanks to composition and we have managed to do it in such a way that there are no SRP violations either!

Sunday, January 24, 2010

Moving my blog.

As of today I will be blogging on an internally managed blog site at Intertech (  I will not be moving existing content but I will continue to update the links on my design and code review check list until it is complete.

Saturday, December 26, 2009

Design Review and Delegation Vs. Inheritance

This week I want to discuss another bullet from my code review checklist

Consider delegation over inheritance.  I have had some pretty heated debates on this topic in the past and I will even take it a step further and say the rule should state that we should favor delegation over inheritance.  Let’s consider the following classic (and intuitive) person/student/teacher example.  A class diagram might look something like this


Person is our base class; Teacher and student derive from person.  We can say that a student Is A person and that a Teacher Is A person.

The up-side of this design is it is simple, intuitive, and it will perform well.  The down side of this approach is that there is a tight coupling between the derived classes and the base class, we are breaking encapsulation by making the functionality of the derived class dependent on the functionality in the base class, and we may even break encapsulation on our Person class by using protected or public access modifiers where we normally wouldn’t do so. 

The problem with breaking encapsulation is that making a change to one class (our base class) can cause unintended changes in other consuming classes (our derived classes).  I can’t begin to tell you how many times I have seen a seemingly small change to a base class break huge pieces of an application.

Now let’s consider using delegation rather than inheritance.  We will change our class diagram to look like the following:


We can say a teacher Has A person and similarly student Has A person.

The down-side of this design is that we have to write more code to create and manage the person class and thus the code will not perform as well (though in most cases I suspect the performance hit is negligible).  We also cannot use polymorphism - we cannot treat a student as a person and we cannot treat a teacher as a person.  The up-side of this design is that we can decrease coupling by defining a person interface and using the interface as the return type for our Person property rather than the concrete Person class, and our design is more robust.  When we use delegation we can have a single instance of a person act as both a student and a teacher.  Try that in C# using the inheritance design!


Saturday, December 12, 2009

Design Review and the DRY Principle

DRY in the DRY principle is an acronym for Don’t Repeat Yourself.  While we are going to focus on applying the principle to code, it can and should be applied to more than just code.  The can be applied to database schemas, tests, documentation, test plans, design documents, build scripts and more.  Any time we start duplicating our work we are signing up for parallel maintenance and chances are we will eventually have the items fall out of synch.

We can use several techniques to avoid duplicate code.  Some obvious things we can do include using classes and methods to organize common code.  We can write an abstract or base class to implement common behaviors for multiple derived classes. 

We can use properties to perform a validation in one place rather than performing the validation anywhere we want to use a member variable:

Code Snippet

  1.         [System.Diagnostics.DebuggerBrowsable(System.Diagnostics.DebuggerBrowsableState.Never)]
  2.         int aComplexInteger;
  3.         public int AComplexInteger
  4.         {
  5.             get { return aComplexInteger; }
  6.             set
  7.             {
  8.                 if (value == 0)
  9.                     throw new ArgumentOutOfRangeException("AComplexInteger");
  10.                 if (value != aComplexInteger)
  11.                 {
  12.                     aComplexInteger = value;
  13.                     //Maybe raise a value changed event
  14.                 }
  15.             }
  16.         \

One of my favorite techniques is constructor chaining.  If we have multiple constructors that perform similar logic , we should use constructor chaining to avoid duplicating code:

Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace CicMaster
  6. {
  7.     class BetterConstructorLogic
  8.     {
  9.         #region WhyItIsBetter
  10.         //No duplicate code, this is called constructor chaining
  11.         //step through this
  12.         #endregion
  13.         string someString = string.Empty;
  14.         int someInteger = 0;
  15.         List<int> myIntegers = new List<int>();
  16.         public BetterConstructorLogic():this("A Default Value")
  17.         {
  18.             //someString = "A Default Value";
  19.             System.Diagnostics.Debug.WriteLine("In Default Constructor");
  20.         }
  21.         public BetterConstructorLogic(string aString):this(aString,123)
  22.         {
  23.             //someInteger = 123;
  24.             System.Diagnostics.Debug.WriteLine("In one param constructor");
  25.         }
  26.         public BetterConstructorLogic(string aString, int anInteger)
  27.         {
  28.             System.Diagnostics.Debug.WriteLine("In two param constructor");
  29.             someString = aString;
  30.             someInteger = anInteger;
  31.             myIntegers.Add(someInteger);
  32.             myIntegers.Add(someInteger ^ 3);
  33.             myIntegers.Add((int)(2 * 3.14 * someInteger));
  34.         }
  35.     }
  36. }

The final technique I would like to mention is use a factory to create all but the simplest objects.  The following (admittedly nonsensical) code needs to execute maybe a half dozen lines of code to construct an Order object. 

Code Snippet

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. namespace BusinessLayer
  7. {
  8.     class ObjectContext
  9.     {
  10.         public ObjectContext(String username)
  11.         {
  12.             //Look up the user permissions
  13.         }
  14.         public bool IsInTranaction { get; set; }
  15.         public bool BeginTransaction()
  16.         {
  17.             //do some transaction logic
  18.             return true;
  19.         }
  20.     }
  21.     class Order
  22.     {
  23.         public Order(ObjectContext theContext)
  24.         {
  25.         }
  26.     }
  27.     class Consumer
  28.     {
  29.         public Consumer()
  30.         {
  31.             ObjectContext ctx = new ObjectContext(Thread.CurrentPrincipal.Identity.Name);
  32.             if (!ctx.IsInTranaction)
  33.             {
  34.                 if (ctx.BeginTransaction())
  35.                 {
  36.                     //...
  37.                 }
  38.             }
  39.             Order order = new Order(ctx);
  40.         }
  41.     }
  42. }

Duplicating these few lines of code in a couple places is not that difficult.  Now say the application is enhanced and grows for a few years and suddenly we see this code duplicated dozens or hundreds of times.  At some point it is likely that we want to change the construction logic, finding and changing all the code we use to create the order is difficult, time consuming, and a QA burden. 

A better approach would be to encapsulate the logic required to build a new order.  Here is an implementation using a simple factory.  It is much easier to find, change, and test this code:

Code Snippet

  1.     static class OrderFactory
  2.     {
  3.         public static Order GetOrder()
  4.         {
  5.             ObjectContext ctx = new ObjectContext(Thread.CurrentPrincipal.Identity.Name);
  6.             if (!ctx.IsInTranaction)
  7.             {
  8.                 if (ctx.BeginTransaction())
  9.                 {
  10.                     //...
  11.                 }
  12.             }
  13.             return new Order(ctx);
  14.         }
  15.     }
  16.     class DryConsumer
  17.     {
  18.         public DryConsumer()
  19.         {
  20.             Order order = OrderFactory.GetOrder();
  21.         }
  22.     \

If we recognize that we are duplicating even a few lines of code over and over we need to take a serious look at the code and figure out a way to encapsulate the logic.


My design review checklist