We Don’t Need Another Hero

Filed Under (Uncategorized) by John Miller on 28-07-2009

Tagged Under :

I just began reading Brownfield Application Development in .Net and came across a statement that I found very interesting.

"We Don’t Need Another Hero"

The book does an awesome job describing something called the "Hero Programmer Syndrome". This is defined as someone who will do whatever it takes to meet ridiculous deadlines. They may come in early, stay late, trade family time for work time, etc. They are usually the only person on the team with working knowledge of how the many parts of an system work together. They make sure stuff gets done. And when they produce super-human results, they (not the team) are rewarded by management.

A team will actually run more efficiently if the responsibilities (and resulting glories) are spread out across the entire team. This creates a feeling of collective-ownership which empowers all team members to take pride in the application being developed as well as get them to learn about the entire application stack instead of just focusing on their own little piece of the pie. It also makes adapting to change much easier if management can depend on any member of the team to get a task done instead of just the "hero developer".

I’m only in the first chapter, but so far this book has been a great read!

DotNetKicks Image

Share/Save/Bookmark

Comparing Design Patterns in Ruby and C#: The Composite Pattern

Filed Under (.Net, Ruby) by John Miller on 22-07-2009

Tagged Under : , , ,

In the last post of the series, we took a look at the Observer pattern. This time we’re going to explore the Composite pattern. The Composite pattern gives us the ability to take a complex procedure that may involve many steps and turn it into something that is simple for consumers to use.

The classic definition of the Composite pattern involves three pieces: Component, Leaf, and Composite Component. The component defines the interface that the units (leaves and\or composite components) must implement. A leaf is an implementation of a component that performs work. The composite component also implements the component interface but that’s where the similarities end. Under the covers, it contains a collection of components which could be leaves on nested composites. When an interface method is called, it delegates the call to it’s child components. This may sound more complicated than it actually is. Let’s take a look at an example to see how this could work.

C# Example

In this example, we’re going to take the process of changing a car’s oil and break it down to a group of independent tasks. Following our definition above, let’s define an IComponent interface. Per the contract of this interface, all of our “task” objects will need to include a PerformTask() method.


public interface IComponent
{
    void PerformTask();
}

Next, we’re going to create a base class for the tasks that are made up of a collection of child tasks. Notice that although it implements the PerformTask() method of the IComponent interface, it actually delegates the work to it’s child components.


public abstract class CompositeComponent : IComponent
{
    private IList<IComponent> _tasks = new List<IComponent>();

    public void PerformTask()
    {
        foreach (var task in _tasks)
            task.PerformTask();
    }

    public void AddTask(IComponent task)
    {
        _tasks.Add(task);
    }

    public void RemoveTask(IComponent task)
    {
        _tasks.Remove(task);
    }
}

Now let’s create our first needed task (aka. leaf). This one represents the draining of the old oil in the vehicle.


public class DrainOldOilTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine("Draining old oil.");
    }
}

The next step is to replace the oil filter which is made of two steps, removing the old filter and installing the new one. To demonstrate this, we’ll create a new CompositeComponent subclass.


public class RemoveOldFilterTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine("Removing old filter.");
    }
}

public class InstallNewFilterTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine("Installing new filter.");
    }
}

public class ReplaceFilterTask : CompositeComponent
{
    public ReplaceFilterTask()
    {
        AddTask(new RemoveOldFilterTask());
        AddTask(new InstallNewFilterTask());
    }
}

Last, we need to create a task for adding the new oil as well as a composite “ChangeOil” task that ties it all together. Notice that the ChangeOil object is composed of both regular tasks (DrainOilTask and AddNewOilTask) as well as a composite task (ReplaceFilterTask).


public class AddNewOilTask : IComponent
{
    public void PerformTask()
    {
        Console.WriteLine("Adding new oil.");
    }
}

public class ChangeOil : CompositeComponent
{
    public ChangeOil()
    {
        AddTask(new DrainOldOilTask());
        AddTask(new ReplaceFilterTask());
        AddTask(new AddNewOilTask());
    }
}

Now the entire process is a simple method call.


new ChangeOil().PerformTask();

Output
Draining old oil.
Removing old filter.
Installing new filter.
Adding new oil.

Ruby Example

With Ruby, we no longer need to define a component interface. We just need ensure that our classes define a perform_work() method. We will, however, want to create a base class for our composite components.


class CompositeComponent
  def initialize
    @tasks = []
  end

  def perform_task
    @tasks.each {|task| task.perform_task}
  end

  def add_task(task)
    @tasks << task
  end

  def remove_task(task)
    @tasks.delete task
  end
end

Now we’ll create our task objects. Besides basic syntax, the structure of these classes are pretty much the same C# versions.


class DrainOldOilTask
  def perform_task
    puts "Draining old oil."
  end
end

class RemoveOldFilterTask
  def perform_task
    puts "Removing old filter."
  end
end

class InstallNewFilterTask
  def perform_task
    puts "Installing new filter."
  end
end

class ReplaceFilterTask < CompositeComponent
   def initialize
     super
     add_task RemoveOldFilterTask.new
     add_task InstallNewFilterTask.new
   end
end

class AddNewOilTask
  def perform_task
    puts "Adding new oil."
  end
end

class ChangeOil < CompositeComponent
   def initialize
     super
     add_task DrainOldOilTask.new
     add_task ReplaceFilterTask.new
     add_task AddNewOilTask.new
   end
end

Using the objects is also very much the same.


ChangeOil.new.perform_task

Output
Draining old oil.
Removing old filter.
Installing new filter.
Adding new oil.

As you can see, implementing the pattern in the two languages is pretty similar. The biggest difference is the lack of need for a component interface within the Ruby example.

Next time, we’ll be looking at the Iterator pattern. Stay tuned!

kick it on DotNetKicks.com

Share/Save/Bookmark

Comparing Design Patterns in Ruby and C#: The Observer Pattern

Filed Under (.Net, Ruby) by John Miller on 15-07-2009

Tagged Under : , , ,

Continuing our comparison of design patterns in Ruby and C#, we’re taking a look at the Observer pattern. With this pattern, we have a subject and a list of observers that are interested in knowing when changes occur on the subject. This happens in a push model, the subject maintains the list observers and notifies each when needed.

In our examples, we’re going to create a Vehicle object that contains a couple of key properties, Mileage and MileageAtLastOilChange. When a new Vehicle instance is created both properties start at zero. As the vehicle’s Drive() method is called and miles are added to it, it notifies any known observers. The MilesUntilNextOilChange property lets others know how long the vehicle can be driven until it should get an oil change. When the PerformOilChangeMethod() is called, the MileageAtLastOilChange property is set to the current mileage and registered observers are notified that changes occurred.

We are also going to create a Dashboard object that will let us know how many miles the vehicle can be driven until it needs it’s next oil change as well as a warning message alerting the driver that it needs a oil change when it reaches 3000 miles.

C# Example

First we’ll create our Vehicle object as well as an IVehicleObserver interface that must be implemented by any Vehicle observers. Note that the Vehicle object contains an AddObserver() that allows observers to register themselves with the Vehicle.


using System.Collections.Generic;

namespace DesignPatterns.ObserverPattern
{
    public class Vehicle
    {
        private IList<IVehicleObserver> _observers = new List<IVehicleObserver>();

        public int Mileage { get; private set; }
        public int MileageAtLastOilChange { get; private set; }
        public int MilesUntilNextOilChange { get { return 3000 - (Mileage - MileageAtLastOilChange); } }

        public Vehicle()
        {
            Mileage = 0;
            MileageAtLastOilChange = 0;
        }

        public void Drive(int miles)
        {
            Mileage += miles;
            NotifyObservers();
        }

        public void PerformOilChange()
        {
            MileageAtLastOilChange = Mileage;
            NotifyObservers();
        }

        public void AddObserver(IVehicleObserver observer)
        {
            _observers.Add(observer);
        }

        private void NotifyObservers()
        {
            foreach (var observer in _observers)
                observer.Notify(this);
        }
    }
}

namespace DesignPatterns.ObserverPattern
{
    public interface IVehicleObserver
    {
        void Notify(Vehicle vehicle);
    }
}

And now we’ll create our Dashboard class which will implement the IVehicleObserver interface. When the Notify() method is called, it updates the Message property to reflect the vehicle’s current status.


namespace DesignPatterns.ObserverPattern
{
    public class Dashboard : IVehicleObserver
    {
        public string Message { get; private set; }

        public Dashboard()
        {
            Message = string.Empty;
        }

        public void Notify(Vehicle vehicle)
        {
            Message = vehicle.MilesUntilNextOilChange <= 0
                      ? "Time for an oil change!"
                      : string.Format("Next oil change is due in {0} miles.", vehicle.MilesUntilNextOilChange);
        }
    }
}

Let’s take a look at how these two will work together.


var dashboard = new Dashboard();
var vehicle = new Vehicle();

vehicle.AddObserver(dashboard);

vehicle.Drive(2000);
Console.WriteLine(dashboard.Message);

vehicle.Drive(1500);
Console.WriteLine(dashboard.Message);

vehicle.PerformOilChange();
Console.WriteLine(dashboard.Message);

vehicle.Drive(1000);
Console.WriteLine(dashboard.Message);

Ruby Example

The Ruby example really isn’t that much unlike the C# version. The big difference is that we don’t need to create an IVehicleObserver interface, we just need to make sure our Dashboard object has a “notify” method that accepts a Vehicle object.


class Vehicle
  attr_reader :mileage, :mileage_at_last_oil_change

  def initialize
    @mileage = 0
    @mileage_at_last_oil_change = 0
    @observers = []
  end

  def drive(miles)
    @mileage += miles
    notify_observers
  end

  def miles_until_next_oil_change
    3000 - (@mileage - @mileage_at_last_oil_change)
  end

  def perform_oil_change
    @mileage_at_last_oil_change = @mileage
    notify_observers
  end

  def add_observer(observer)
    @observers << observer
  end

  private

  def notify_observers
    @observers.each {|observer| observer.notify self}
  end
end

class Dashboard
  attr_reader :message

  def initialize
    @message = ""
  end

  def notify(vehicle)
    @message = vehicle.miles_until_next_oil_change <= 0 ?
                "Time for an oil change!" :
                "Next oil change is due in #{vehicle.miles_until_next_oil_change} miles."
  end
end

And using the objects is very similiar to the C# example as well.


require "dashboard"
require "vehicle"

dashboard = Dashboard.new
vehicle = Vehicle.new

vehicle.add_observer dashboard

vehicle.drive 2000
puts dashboard.message

vehicle.drive 1500
puts dashboard.message

vehicle.perform_oil_change
puts dashboard.message

vehicle.drive 1000
puts dashboard.message

Simplifying Our Objects

Both languages have built-in mechanisms that we can take advantage of that can make implementing the Observer pattern easy.

In .Net, we’re given out-of-the-box event handling. We just need to create a delegate that defines the method our observers will use for receiving notifications. This reduces the need for an IVehicleObserver interface and simplifies our design.


public delegate void MilesChangedHandler(Vehicle vehicle);

public class Vehicle
{
    public int Mileage { get; private set; }
    public int MileageAtLastOilChange { get; private set; }
    public int MilesUntilNextOilChange { get { return 3000 - (Mileage - MileageAtLastOilChange); } }
    public event MilesChangedHandler MilesChangedEvent;

    public Vehicle()
    {
        Mileage = 0;
        MileageAtLastOilChange = 0;
    }

    public void Drive(int miles)
    {
        Mileage += miles;
        NotifyObservers();
    }

    public void PerformOilChange()
    {
        MileageAtLastOilChange = Mileage;
        NotifyObservers();
    }

    private void NotifyObservers()
    {
        if (MilesChangedEvent != null)
            MilesChangedEvent(this);
    }
}

And no changes have to be made to our Dashboard object.


public class Dashboard : IVehicleObserver
{
    public string Message { get; private set; }

    public Dashboard()
    {
        Message = string.Empty;
    }

    public void Notify(Vehicle vehicle)
    {
        Message = vehicle.MilesUntilNextOilChange <= 0
                             ? "Time for an oil change!"
                             : string.Format("Next oil change is due in {0} miles.", vehicle.MilesUntilNextOilChange);
    }
}

Using the classes changes a bit, note how we subscribe to event on the Vehicle object.


var dashboard = new Dashboard();
var vehicle = new Vehicle();

vehicle.MilesChangedEvent += dashboard.Notify;

vehicle.Drive(2000);
Console.WriteLine(dashboard.Message);

vehicle.Drive(1500);
Console.WriteLine(dashboard.Message);

vehicle.PerformOilChange();
Console.WriteLine(dashboard.Message);

vehicle.Drive(1000);
Console.WriteLine(dashboard.Message);

Ruby also has some built goodness to make our work a little easier. We are actually given an Observable module that we can add to our Vehicle class that will handle the adding, removing, and notifying of observers. The only minor addition we need to add to our object is the a call to the “changed” method when we want to indicate that our object’s state has changed.


require "observer"

class Vehicle
  include Observable

  attr_reader :mileage, :mileage_at_last_oil_change

  def initialize
    @mileage = 0
    @mileage_at_last_oil_change = 0
    @observers = []
  end

  def drive(miles)
    @mileage += miles
    changed
    notify_observers self
  end

  def miles_until_next_oil_change
    3000 - (@mileage - @mileage_at_last_oil_change)
  end

  def perform_oil_change
    @mileage_at_last_oil_change = @mileage
    changed
    notify_observers self
  end
end

To use the module, our observers have to have an “update” method so we’ll need to rename our “notify” method on the Dashboard object.


class Dashboard
  attr_reader :message

  def initialize
    @message = ""
  end

  def update(vehicle)
    @message = vehicle.miles_until_next_oil_change <= 0 ?
                "Time for an oil change!" :
                "Next oil change is due in #{vehicle.miles_until_next_oil_change} miles."
  end
end

And our usage stays exactly the same!


require "dashboard"
require "vehicle"

dashboard = Dashboard.new
vehicle = Vehicle.new

vehicle.add_observer dashboard

vehicle.drive 2000
puts dashboard.message

vehicle.drive 1500
puts dashboard.message

vehicle.perform_oil_change
puts dashboard.message

vehicle.drive 1000
puts dashboard.message

That’s it for the Observer pattern, next time we’ll take a look at the Composite pattern.

kick it on DotNetKicks.com

Share/Save/Bookmark

Comparing Design Patterns in Ruby and C#: The Strategy Pattern

Filed Under (.Net, Ruby) by John Miller on 03-07-2009

Tagged Under : , , ,

In the previous post of this series, we looked at how the Template pattern is implemented in both Ruby and C#. In this post, we’ll take a look at the Strategy pattern…one of my favorites.

In it’s classic form, the Strategy pattern consists of a context class and various “strategies” which share a common interface. The context class is given a strategy to which it can delegate work to. Think of it as passing an algorithm to a class. To change the way the class works, change the algorithm you feed it. This makes it really easy to adhere to the open-closed principle which states that an object should be open for extension but closed for modification. We can drastically change how our class operates without changing a line of code in the class itself.

In .Net, the Sort method on generic lists is a perfect example of how the Strategy pattern can be applied. To change how the list is sorted, you simply pass in a method that matches the Comparison<T> delegate or a class that implements IComparer<T>. (See my earlier post on the various ways you can sort a generic list in .Net).

Ruby has a really cool example built in as well with it’s rdoc utility which uses strategies both for distilling documentation from various languages (C, Ruby, etc) and in how it ouputs the documentation (HTML, XML, CHM).

In our examples below, we’re creating a Driver object that has three different properties: DrivingHabit, MilesDriven, and SpeedingTickets. It also has a method “Drive” which accepts the number of hours that the driver should drive as a parameter. The Drive method delegates the actual "driving” logic to the driving habit that it is composed with. A cautious driver follows the speed limit (55mph) and never gets a speeding ticket. A reckless driver, however, travels along at 80mph and gets a speeding ticket every 1/2 hour.

C# Example

For the Strategy pattern to work in a static language, we must first define a contract that the strategies themselves must adhere to as well as the context class. So we’ll start by creating the Driver object and defining the IDrivingHabit interface.


namespace DesignPatterns.StategyPattern
{
    public class Driver
    {
        public IDrivingHabit DrivingHabit { get; set; }
        public int MilesDriven { get; set; }
        public int SpeedingTickets { get; set; }

        public Driver(IDrivingHabit drivingHabit)
        {
            DrivingHabit = drivingHabit;
        }

        public void Drive(int hours)
        {
            DrivingHabit.Drive(this, hours);
        }
    }
}

namespace DesignPatterns.StategyPattern
{
    public interface IDrivingHabit
    {
        void Drive(Driver driver, int duration);
    }
}

Now let’s create our strategies.


namespace DesignPatterns.StategyPattern
{
    public class CautiousDrivingHabit : IDrivingHabit
    {
        public void Drive(Driver driver, int hours)
        {
            driver.MilesDriven =  hours * 55;
        }
    }
}

namespace DesignPatterns.StategyPattern
{
    public class RecklessDrivingHabit : IDrivingHabit
    {
        public void Drive(Driver driver, int hours)
        {
            driver.MilesDriven += hours * 80;
            driver.SpeedingTickets += hours * 2;
        }
    }
}

And to see how this would actually be used, we’ll take a look at the unit tests.


using NUnit.Framework;

namespace DesignPatterns.StategyPattern
{
    [TestFixture]
    public class When_a_cautious_driver_is_on_the_road_for_3_hours
    {
        private Driver granny;

        [SetUp]
        public void EstablishContext()
        {
            granny = new Driver(new CautiousDrivingHabit());
            granny.Drive(3);
        }

        [Test]
        public void Should_move_a_total_of_165_miles()
        {
            Assert.That(granny.MilesDriven, Is.EqualTo(165));
        }

        [Test]
        public void Should_not_receive_any_speeding_tickets()
        {
            Assert.That(granny.SpeedingTickets, Is.EqualTo(0));
        }
    }

    [TestFixture]
    public class When_a_reckless_driver_is_on_the_road_for_3_hours
    {
        private Driver speedRacer;

        [SetUp]
        public void EstablishContext()
        {
            speedRacer = new Driver(new RecklessDrivingHabit());
            speedRacer.Drive(3);
        }

        [Test]
        public void Should_move_a_total_of_240_miles()
        {
            Assert.That(speedRacer.MilesDriven, Is.EqualTo(240));
        }

        [Test]
        public void Should_receive_a_speeding_ticket_for_every_half_hour_on_the_road()
        {
            Assert.That(speedRacer.SpeedingTickets, Is.EqualTo(6));
        }
    }
}

Pretty simple, eh? Let’s take a look at how we would do this in Ruby.

Ruby Example

First, we’ll create the Driver object. So far doesn’t seem that much different from the C# example.


class Driver
  attr_accessor :driving_habit, :miles_driven, :speeding_tickets

  def initialize(driving_habit)
    @driving_habit = driving_habit
    @miles_driven = 0
    @speeding_tickets = 0
  end

  def drive(hours)
    @driving_habit.drive self, hours
  end
end

Next we’re going to jump straight into creating our Strategy classes. Since Ruby supports duck typing, we really have no need to create an object that defines what our strategies should look like. We could define a base DrivingHabit object that included a Drive method that we can override in our implementations, but that would be producing extra code for no added benefit. We’re ok as long as the object we pass in has a Drive method that matches the required signature.


class CautiousDrivingHabit
  def drive(driver, hours)
    driver.miles_driven += hours * 55
  end
end

require 'lib/driver'

class RecklessDrivingHabit
  def drive(driver, hours)
    driver.miles_driven += hours * 80
    driver.speeding_tickets += hours * 2
  end
end

And now we’ll take a look at the corresponding unit tests.


require 'lib/cautious_driving_habit'

describe "When a cautious driver is on the road for 3 hours" do
  before(:each) do
    @granny = Driver.new(CautiousDrivingHabit.new)
    @granny.drive 3
  end

  it "should move a total of 165 miles" do
    @granny.miles_driven.should == 165
  end

  it "should not receive any speeding tickets" do
    @granny.speeding_tickets.should == 0
  end
end

require 'lib/reckless_driving_habit'

describe "When a reckless driver is on the road for 3 hours" do
  before(:each) do
    @speed_racer = Driver.new(RecklessDrivingHabit.new)
    @speed_racer.drive 3
  end

  it "should move a total of 240 miles" do
    @speed_racer.miles_driven.should == 240
  end

  it "should not receive a speeding ticket for every half hour on the road" do
    @speed_racer.speeding_tickets.should == 6
  end
end

Simplifying the Strategy Pattern

For simple scenarios (such as this one) where the strategies are extremely basic, we can actually reduce the need for the strategy classes themselves. In C#, we just need to add an overloaded Drive method that accepts a delegate that matches the Drive method in the IDrivingHabit interface. (We could have changed the contructor to do this instead.)


public void Drive(int hours, Action<Driver, int> drivingHabit)
{
     drivingHabit(this, hours);
}

And to use it, we pass a lambda expression in that contians our logic.


speedRacer.Drive(3, (driver, hours) =>
                     {
                          driver.MilesDriven += hours*80;
                          driver.SpeedingTickets += hours*2;
                     });

We can do something very similiar in Ruby. We’ll create a new method that accepts a code block as a second parameter. Note that we had to create a new name for this method (Ruby doesn’t support method overloading).


def drive_using_habit(hours, &amp;amp;driving_habit)
 driving_habit.call self, hours
end

And the code using this.


@speed_racer.drive_using_habit(3) do |driver, hours|
    driver.miles_driven += hours * 80
    driver.speeding_tickets += hours * 2
end

In the next post, we’ll take a look at a very similiar pattern, the Observer pattern.

kick it on DotNetKicks.com

Share/Save/Bookmark

Challenge Yourself This Year: July Goals Progress

Filed Under (Uncategorized) by John Miller on 02-07-2009

Tagged Under : ,

Earlier in the year I made a list of goals I wanted to accomplish this year and decided to publish my progress periodically here…to produce some sort of accountability. And as usual, seeing Darrell’s update made me realize that it’s been way to long since my last update!

Technical Goals

Read the following books:

Become proficient with the following tools & technologies:

  • ASP.Net MVCNo progress, hopefully in the next few months…
  • NHibernateFinished! Used NHibernate in my first project a couple of months ago and was blown away by it’s awesomeness!
  • The Castle StackFinished! Used Windsor on a recent project and explored ActiveRecord. Believe this is as far as I want to go with Castle this year.
  • Team CityFinished! Set up Team City for several projects in the last few months.
  • Ruby (the basics at a minimum)Finished (but still learning)! My goal was to just learn the basics, actually taking that a step further and am working on an actual Rails project with a Josh.
  • PowershellNo progress here.

Get involved:

  • Two blog posts per month – I more or less went silent in the last two months and hope to kick myself back into gear over the weekend. Started a series of posts comparing design pattern implementations in Ruby and C#, but only finished the first one (Template pattern). Will be continuing this series very soon. I promise.
  • Two technical presentations for coworkers to push agile methodologies at my current company. – Our company has gone through some changes and I don’t see after hours presentations like this happening in the near future, so I’m gonna scratch this one for now.

Certifications:

  • Upgrade MCPD certification from 2.0 to 3.5 – No progress here.

Personal Goals

Family Time

  • Take 2 one week long trips – We took a trip to Disney World last month (which was a blast!) and are hoping to take another long vacation in the next few months.
  • Take 6 weekend getaways – Way behind on this one, believe we’ve taken one so far this year.
  • By the end of the year, work from home regularly two times per week – This is a tough one with my current job, the ability to do this is completely dependant on the project\client and hasn’t been an option lately.

Belief System

  • Read the Bible completely through – I just finished II Kings so my guess is that put’s me at around 30% complete…and 50% of the year is gone already.

Financial

  • Reduce debt by two-thirds – Surprisingly still on track here, it’s forced us to live paycheck to paycheck but it feels good to see substantial progress being made!
  • Become familiar with some of the ins and outs of day trading, as well as how currency trading works – No longer as interested in stocks at the moment, mostly because almost all of our spare money is going to debt reduction. May pick interest up again next year.

Side Projects

  • Finish the project I’ve been working on for the last year! – Almost done, hope to launch this month!!
  • Start a new venture and grow it to produce $500 per month of automated income by the end of the year. – Still working on a project with Josh, may not turn a profit this year but we’ll see.

Looks like I’m really falling behind in my reading (although I’ve been reading things here and there, they just haven’t been books on my list). Planning to change that in the second half of the year.

DotNetKicks Image

Share/Save/Bookmark