Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts

Thursday, July 22, 2010

The evil of process over craftsmanship

If you had a choice between a well build home that cost more money but wasn’t going to cost very much to maintain or a house that didn’t cost very much, but was going to cost a lot more to maintain in the long run, which would you choose.  If you own a house and have had to deal with the upkeep of the home I can almost guarantee you would much rather have the first house, even if fixing the major problems is free (most new houses come with a one year guarantee from the builder), if you have ever had to deal with getting your builder to fixed things, free or not, the stress and aggravation almost makes it not worth it.  So why do so many software development teams almost insist on building software like how the second house was built.

By taking the time to build a quality product, it will cost more up front, talented people cost money, to do the job right takes time(time=money) but because it was done right the first time it costs a lot less in the long run. 
Unfortunately in the software development world it’s far to common to just get it out and worry about fixing known problems later.  This becomes even more painful when the schedule or process becomes the reason for poor craftsmanship.

Here are two problems, one is building a house the other is building software:

1) A builder starts working on a house and discovers that the property has a high water table and that every spring there would be flooding in the crawlspace.  The two ways to solve this problem are: bring in enough dirt to raise the house up so the crawlspace doesn't get flooded or add subpumps to pump the water out.  Both fix the problem, while the subpumps are going to be quicker to setup, it’s not going to get out all of the water and it will add to maintenance costs which in the long run will be much more expensive.

2) A pair of developers are tasked with writing a service for importing data into a database and half way though writing it they find out the data has duplicate records and some other garbage data.  There are two ways to solve this, build a validator to remove the garbage data or pass it off and have the DBAs create a job to remove the garbage from the database.

I’m fairly sure we would all much rather take the time to put in the fill dirt then have to deal with the maintenance of having sub pumps, and yet for some reason it’s very common for developers to be told “we don’t have time to add a filter” and to push the task of removing the garbage from the database onto the DBAs, or worse yet just live with the garbage data.

We know that when the process(schedule/tasking) trumps craftsmanship(using subpumps or having the DBAs remove bad data) you end up with a lower quality product with higher overall costs so why do we still do it?
The tools of the software craftsman: TDD, design patterns(command, strategy, observer, etc ), decoupled design, source control, continues integration, paired programming, etc.  and by using any of them you will end up with better software with lower overall costs and yet it feels like it’s a constant battle to get them into our development process.  We need to take a stand, we need to be craftsman and insist on building quality products.

Friday, May 28, 2010

Using the Observer Pattern

At work we are reading “Head First Design Patterns” and discussing the “Observer Pattern” and some people wanted to see a code example.
The first part is the the class that manages the observer classes
   1: public class EventManager<T>
   2: { 
   3:     private Dictionary<string, ISubscriber<T>> _subscribers = new Dictionary<string, ISubscriber<T>>();
   4:     public Dictionary<string,ISubscriber<T>> Subscribers
   5:     {
   6:         get { return _subscribers; }
   7:         set { _subscribers = value; }
   8:     }
   9:  
  10:     public void Notify(T newState)
  11:     {
  12:         foreach (var observer in Subscribers.Values)
  13:         {
  14:             observer.State = newState;
  15:             observer.Update();
  16:         }
  17:     }
  18: }
In this example I created a generic class that has two basic parts a collection of subscribers or observers and a method that loops though and updates the state of the subscribers.  I used a Dictionary<string,ISubscriber<T>> to make it easy to manage my subscribers based on a key, and because ISubscriber<T> is also a generic its a very flexible and strongly typed way to work with the subscribers.

Next let’s take a look at ISubscriber<T> interface
   1: public interface ISubscriber<T>
   2: {
   3:     T State { get; set; }
   4:     void Update();
   5: }
it’s that simple, I use generics to determine the state and the input type for the update method, here is an example implementation
   1: public class TweetLocation : ISubscriber<Location>
   2: {
   3:     public ITwitter TwitterInterfacer = new FakeTwitterClient();
   4:     public Location State { get; set; }
   5:  
   6:     public void Update()
   7:     {
   8:         TwitterInterfacer.TweetMessage(string.Format("currently at ({0},{1})",State.Lat,State.Lon));
   9:     }
  10: }
TweetLocation is observing Location information and calls a Twitter class to Tweet the new location when updated, for something a little more complex
   1: public class SaveLocation : ISubscriber<Location>
   2: {
   3:     public ILocationReposigtory LocationRepository = new FakeLocationRepository();
   4:     public static EventManager<string> ErrorHandler = new EventManager<string>();
   5:  
   6:     public Location State{get;set;}
   7:  
   8:     public SaveLocation()
   9:     {
  10:         ErrorHandler.Subscribers.Add("ErrorMailer",new ErrorMailer());
  11:     }
  12:  
  13:     public void Update()
  14:     {
  15:         bool success = LocationRepository.SaveLocation(State);
  16:         if (!success)
  17:         {
  18:             ErrorHandler.Notify("Failed to save location");
  19:         }
  20:     }
  21: }
SaveLocation is basically the same as TweetLocation except it has it’s own EventManager to handle errors from failed attempts at saving the location.

Finally here is an example of actually using it
   1: class Program
   2: {
   3:     public static EventManager<Location> LocationHandler = new EventManager<Location>();
   4:  
   5:     static void Main(string[] args)
   6:     {
   7:         LocationHandler.Subscribers.Add("Repository",new SaveLocation());
   8:         LocationHandler.Subscribers.Add("Twitter",new TweetLocation());
   9:  
  10:         Location currentLocation = new Location(){Lat = 111,Lon = -121};
  11:  
  12:         LocationHandler.Notify(currentLocation);
  13:  
  14:         Console.ReadKey();
  15:  
  16:         currentLocation.Lon = 1211;
  17:         LocationHandler.Subscribers.Remove("Twitter");
  18:         LocationHandler.Notify(currentLocation);
  19:  
  20:         Console.ReadKey();
  21:         
  22:         
  23:     }
  24: }
This is a simple console app that demonstrates adding subscribers, updating state, and removing a subscriber. 

A real world example of using “Observer Pattern” is a service bus like NServiceBus or MassTransit, where an event driven application needs to send messages to one or more subscribers.

As always here is a link to the project source.

Monday, January 18, 2010

Unit Testing For Javascript

Recently I had to write some fairly substantial javascript, and in the process I was reminded of how fast javascript, like most scripting languages, and get out of hand really quick. I took a step back and thought why should I work in javascript any different then I do in other language? Just because it’s a scripting language doesn't make it any less valid of a development platform, and I can apply the same design pattern and principles I would with anything else.

So The first thing I did was went looking for a unit testing framework and I found JSUnit. JSUnit is available from http://www.jsunit.net/ and is a port of the JUnit framework to javascript. The entire testing framework and test runner is written in javascript so I can use it anywhere you use javascript and in any development platform(php, ruby, Perl, java, .net, etc).

Getting started I have this javascript function I want to test

   1: function addTwoNumber(x, y) {
   2:     var result = x + y;
   3:     return result;
   4: }

so first I create an html page and add the jsUnitCore.js and my .js file containing this function (almost all of your javascript really should be in .js files for a number of reasons, but that’s another blog post).

   1: <html>
   2:     <head>
   3:         <script language="JavaScript" src="jsUnitCore.js"></script>
   4:         <script language="JavaScript" src="javascriptCode.js"></script>
   5:     </head>
   6:     <body>        
   7:     </body>
   8: </html>

then to add test cases I create functions inside a script tag in the body of the html page like so

   1: <body>
   2:     <script type="text/javascript">
   3:         function test_addTwoNumber_TwoNumbersAreAdded() {
   4:             var result = addTwoNumber(2, 2);
   5:             assertEquals("Adds 2 values together", 4, result);
   6:         }
   7:  
   8:     </script>
   9: </body>
to tag a function as a test, simply start the function off with the text “test” and the test runner will pick it up and run it. The assert is done with the function assertEquals provided by the jsUnitCore.js file and takes 3 prams (test description, expected value, and actual result) and to run the test you simply open the testRunner.html page in the jsunit dir in a browser

image

then add the file location and run the tests, it’s that simple. If you look at the screen shot you will notice that I’m using opera, for what ever reason I couldn’t get the test runner to work in Firefox, every time I would try and run my test file I would get a time out error, The funny thing is it works in IE, Chrome, and Opera just fine, weird.

Wednesday, October 14, 2009

Not ready for Inversion Of Control, just use a factory for now

There has been a lot of discussion latterly in the blog world about using inversion of control or IOC, some claiming it’s to hard to understand, it complicates development, and it’s unnecessary; the other side saying quit complaining it’s not that hard, it enforces good design and makes code more maintainable. To this I’m going to take the vary controversial position that they are both right.

Inversion of control can be intimidation the first time you use it, it adds a bit of complexity and you can write quality applications with out it. On the other side once you “get it” IOC really isn't that hard it encourages separation of responsibilities, and makes it much easier to test making regression testing and refactoring much easier.

So how do we get all of the advantages with out adding all of the complexities of an IOC container, simple just use a software factory class. For those who don’t know, basically a factory class is just away to abstract and consolidate the logic for getting your code dependencies.

Let’s say you have some code for accessing data from Amazon’s simpleDB

   1: public class ContactData : IContactData
   2: {
   3:     private Proxy simpleDBProxy;
   4:     public Proxy SimpleDBProxy
   5:     {
   6:         get
   7:         {
   8:             if (simpleDBProxy==null)
   9:             {
  10:                 simpleDBProxy = new Proxy();
  11:             }
  12:             return simpleDBProxy;
  13:         }
  14:         set
  15:         {
  16:             simpleDBProxy = value;
  17:         }
  18:     }
  19:     const string DomainName = "Contacts";
  20:  
  21:     public Contacts GetContacts()
  22:     {
  23:         Contacts myContacts = new Contacts();
  24:  
  25:         SelectRequest request = new SelectRequest
  26:         {
  27:             SelectExpression = string.Format("SELECT * FROM {0} ", DomainName)
  28:         };
  29:         SelectResponse response = SimpleDBProxy.Service.Select(request);
  30:  
  31:         var contacts = from item in response.SelectResult.Item
  32:                          select new Contact()
  33:                                     {
  34:                                         Email = item.Attribute.GetValueByName("Email"),
  35:                                         Name = item.Attribute.GetValueByName("Name"),
  36:                                         Phone = item.Attribute.GetValueByName("Phone"),
  37:                                         ID =  item.Name
  38:                                     };
  39:         myContacts.AddRange(contacts);
  40:         return myContacts;
  41:     }
  42:  
  43:     public Contacts GetContactsByName(string contactName)
  44:     {
  45:         Contacts myContacts = new Contacts();
  46:  
  47:         SelectRequest request = new SelectRequest
  48:         {
  49:             SelectExpression = string.Format("SELECT * FROM {0} where Name='{1}' ", DomainName, contactName)
  50:         };
  51:         SelectResponse response = SimpleDBProxy.Service.Select(request);
  52:  
  53:         var contacts = from item in response.SelectResult.Item
  54:                        select new Contact()
  55:                        {
  56:                            Email = item.Attribute.GetValueByName("Email"),
  57:                            Name = item.Attribute.GetValueByName("Name"),
  58:                            Phone = item.Attribute.GetValueByName("Phone"),
  59:                            ID = item.Name
  60:                        };
  61:         myContacts.AddRange(contacts);
  62:         return myContacts;
  63:     }
  64:    
  65:     public bool SaveContact(Contact contact)
  66:     {
  67:         List<ReplaceableAttribute> attributeList = new List<ReplaceableAttribute>
  68:            {
  69:                new ReplaceableAttribute().WithName("Email").WithValue(contact.Email),
  70:                new ReplaceableAttribute().WithName("Name").WithValue(contact.Name),
  71:                new ReplaceableAttribute().WithName("Phone").WithValue(contact.Phone)
  72:            };
  73:         contact.ID = Guid.NewGuid().ToString();
  74:         bool success = false;
  75:         try
  76:         {
  77:             if (!SimpleDBProxy.Domains.Contains(DomainName))
  78:             {
  79:                 SimpleDBProxy.AddDomain(DomainName);
  80:             }
  81:             PutAttributesRequest action = new PutAttributesRequest
  82:               {
  83:                   ItemName = contact.ID,
  84:                   Attribute = attributeList,
  85:                   DomainName = DomainName
  86:               };
  87:             PutAttributesResponse response = SimpleDBProxy.Service.PutAttributes(action);
  88:             success = true;
  89:         }
  90:         catch (Exception requestException)
  91:         {
  92:             success = false;
  93:         }
  94:  
  95:         return success;
  96:     }
  97: }

now because this implements the IContactData interface

   1: public interface IContactData
   2: {
   3:     Contacts GetContacts();
   4:     Contacts GetContactsByName(string contactName);
   5:     bool SaveContact(Contact contact);
   6: }

we can use it anywhere we would use IContactData, for example here we have an application that uses both local and remote contacts

   1: public class ContactsRequests
   2: {
   3:     private IContactData ContactData;
   4:     public bool UseLocalContacts { get;set; }
   5:  
   6:     public Contacts SearchContactsByName(string contactName)
   7:     {
   8:         if (UseLocalContacts)
   9:         {
  10:             ContactData = new LocalContactData();
  11:         }
  12:         else
  13:         {
  14:             ContactData = new ContactData();
  15:         }
  16:         return ContactData.GetContactsByName(contactName);
  17:     }
  18:  
  19:     public Contacts GetContacts()
  20:     {
  21:         if (UseLocalContacts)
  22:         {
  23:             ContactData = new LocalContactData();
  24:         }
  25:         else
  26:         {
  27:             ContactData = new ContactData();
  28:         }
  29:         return ContactData.GetContacts();
  30:     }
  31:  
  32:     public bool AddContact(Contact newContact)
  33:     {
  34:         return ContactData.SaveContact(newContact);
  35:     }
  36: }

now this works but there are a few problems, first there is no way to test it’s functionality without testing the functionality of LocalContactData and/or ContactData with a little simple refactoring

   1: public class ContactsRequests
   2: {
   3:     private IContactData contactData;
   4:     public IContactData ContactData
   5:     {
   6:         get
   7:         {
   8:             if (contactData==null)
   9:             {
  10:                 if (UseLocalContacts)
  11:                 {
  12:                     contactData = new LocalContactData();
  13:                 }
  14:                 else
  15:                 {
  16:                     contactData = new ContactData();
  17:                 }
  18:             }
  19:             return contactData;
  20:         }
  21:         set
  22:         {
  23:             contactData = value;
  24:         }
  25:     }
  26:     public bool UseLocalContacts { get;set; }
  27:  
  28:     public Contacts SearchContactsByName(string contactName)
  29:     {          
  30:         return ContactData.GetContactsByName(contactName);
  31:     }
  32:  
  33:     public Contacts GetContacts()
  34:     {
  35:        return ContactData.GetContacts();
  36:     }
  37:  
  38:     public bool AddContact(Contact newContact)
  39:     {
  40:         return ContactData.SaveContact(newContact);
  41:     }
  42: }
we remove the instantiation logic from the method and move it to a public property this way we can set the ContactData property to a mock object and test the specific logic of the methods in this class, now the only problem with this is everywhere we want to use IContactData we have to perform the same logic, and basically reproduce the same code over and over again. This is where factories come in, if we build a factory like this
   1: public static class DataFactories
   2: {
   3:     public static IContactData GetContactInterface(bool isLocal)
   4:     {
   5:         IContactData myContactData;
   6:         if (isLocal)
   7:         {
   8:             myContactData = new LocalContactData();
   9:         }
  10:         else
  11:         {
  12:             myContactData= new ContactData();
  13:         }
  14:         return myContactData;
  15:     }
  16: }

Then we just implement it like this

   1: public IContactData ContactData
   2: {
   3:     get
   4:     {
   5:         if (contactData==null)
   6:         {
   7:             contactData = DataFactories.GetContactInterface(UseLocalContacts);
   8:         }
   9:         return contactData;
  10:     }
  11:     set
  12:     {
  13:         contactData = value;
  14:     }
  15: }

your applications don’t know or care how they got there class for getting contact all they know is they did, where this really comes in handy is if you have to change out how you handle your local contacts from let’s say an xml file to a database, the only place you have to change your code is in the factory.

Congratulations you are now 90% of the way there for using a IOC container, you have a single place for handling all of your instantiation so once you decide to use IOC you just change how the factory works from having logic that decides what class to insatiate to pulling it from the IOC container, it’s that simple.

Truth be told I always start with a factory and then later “IF” I need the functionality of an IOC I’ll add it. In the end an IOC container really isn’t nearly as scary as it seems to be, and in the same token it isn’t nearly a vital as some people would like to claim, it’s a tool that can be used to solve specific problems, but 90% of the same problems can be solved using a factory.