Review: Brownfield Application Development in .Net

Filed Under (.Net) by John Miller on 29-08-2009

Tagged Under : ,

I just finished reading Brownfield Application Development in .Net by Kyle Baley and Donald Belcham and thought I’d put together a quick review some of the strengths and weaknesses the book has to offer.

It’s broken up into two sections with the first half of the book describing how to create a healthy ecosystem for you code to grow in. This gets into areas such as project structure, automated testing, automated builds, continuous integration, etc. They even get into some of the various personas you may run into when working on a Brownfield application (such as the “Ivory Tower Architect” and “The Hero Developer”) and how to effectively work with those personalities. The second half of the book discusses how to make the code itself flexible and maintainable. This includes everything from design patterns to explaining how to create an anti-corruption layer in your code to minimize the impact changes will make on your software in the future.

One of my personal favorite sections included in the book was the awesome explanation of the differences between MVP and MVC patterns. Very clear and concise. I had struggled in the past really understanding the finer points of how the two differed, but the author did a great job comparing the two (as well as their variations).

There are lot of good book available on agile development techniques and software design principles, but this has to be the best I’ve read yet that explains the nuts and bolts of how to apply these ideals to .Net development. There are a lot of great tidbits in there that can be applied to development in any language (although the book is really geared towards tools that are readily available to .Net developers).

And now for a little constructive criticism. The first few chapters, while very informative, seemed to be longer than they should have been. Those could have been reduced by about 25-30% without losing any value. I also felt a little short-changed by it’s explanation of AOP in chapter 8. It started discussing AOP and even gave a code example, but didn’t go deep enough to really explain it clearly. And to be fair, as the book stated, explaining AOP was well beyond the scope of the book, which I fully agree with. But I think that it would have been better to scale back the attempted explanation if it wasn’t going to give a thorough explanation.

All in all though, this is (by far) my favorite .Net specific development book (and I’ve read quite a few!). It offers a lot of practical advice that you can should start applying right away. It hasn’t been released yet, but is available from Manning via their Early Access program. If you’re a .Net developer, regardless of whether or not you’re working on Brownfield applications, I’d highly recommend it!

Share/Save/Bookmark

Comparing Design Patterns in Ruby and C#: The Command Pattern (with Robots!)

Filed Under (.Net, Ruby) by John Miller on 28-08-2009

Tagged Under : , , ,

The command pattern is another one of those patterns that we all (whether we realize it or not) see almost every day. It’s commonly used in UI development but it’s a pattern that can be applied in many situations. In rails, ActiveRecord migrations are a perfect example of a command implementation, including “up” and “down” methods for applying and rolling back a migration respectively.

The beauty of the command pattern is it’s ability to encapsulate complicated logic into an easy to use interface. This usually includes:

  1. An ICommand interface or base class that defines the command structure
  2. Concrete command implementations
  3. A receiver that is fed commands to execute. When these commands are actually executed is completely independent of when the receiver is given the commands. It may choose to execute them right away, but it may just as well decide to hold on to them for later use.

Source Code

All of the code in this example is available to download:

Download the Source

Or, you can pull the source directly from github using the below clone url:

git://github.com/johnmiller/CommandPattern.git

Example Overview

The example below involves a robot that moves around on a XY plane similar to:

XYPlane

The robot is given starting coordinates and moves from there. However, it can only perform certain actions:

  1. Move forward
  2. Turn left
  3. Turn right
  4. Reset

As it is given commands, it stores them in an internal collection. If reset is called, it “undo’s” all the commands executed to that point.

C# Example

The ICommand is pretty simple and only includes two method declarations: Execute() and Undo(). All of our concrete commands will need to implement this interface.


public interface ICommand
{
void Execute();
void Undo();
}

Before we create any concrete command classes, let’s take a look at our Robot class. When a new robot is created, we give it a starting location and direction. Notice that when a user calls ExecuteCommand() it immediately performs the instructions given and then stores the command in an internal list. If Reset() is called it iterates through the list in reverse order and calls Undo() on each.


public class Robot
{
public Location Position { get; set; }
public string Direction { get; set; }
private IList<ICommand> _commandsExecuted = new List<ICommand>();

public Robot(Location position, string direction)
{
Position = position;
Direction = direction;
}

public void ExecuteInstruction(ICommand command)
{
command.Execute();
_commandsExecuted.Add(command);
}

public void Reset()
{
foreach (var command in _commandsExecuted.Reverse())
command.Undo();
}
}

The Robot.Position property is of type Location which is a simple class holding the X and Y coordinates.


public class Location
{
public int X { get; set; }
public int Y { get; set; }

public Location(int x, int y)
{
X = x;
Y = y;
}
}

The first command we’ll look at is the MoveForwardCommand which…moves the robot forward one space. But we need to be sure that the robot is moving forward in the direction that it is facing. Internally it contains a list of algorithms for moving the robot depending on the based on it’s current direction. It can also go backwards if Undo() is called.


public class MoveForwardCommand : ICommand
{
private Robot _robot;
private IDictionary<string, Action<Robot>> _moveActions;

public MoveForwardCommand(Robot robot)
{
_robot = robot;
_moveActions = new Dictionary<string, Action<Robot>>
{
{"N", r => r.Position.Y += 1 },
{"E", r => r.Position.X += 1 },
{"S", r => r.Position.Y -= 1 },
{"W", r => r.Position.X -= 1 }
};
}

public void Execute()
{
_moveActions[_robot.Direction](_robot);
}

public void Undo()
{
var oppositeDirection = Compass.GetOppositeDirection(_robot.Direction);
_moveActions[oppositeDirection](_robot);
}
}

The Undo() method uses a class called Compass to find the backwards direction. This is a simple utility class to aid in finding left, right, and opposite directions. To find the direction to the right or left, we find the current direction’s place in the list and move accordingly. Although we need to ensure that when asked to turn right when facing west, it moves to the start of the list to get north (the opposite holds true when turning left when facing north).


public class Compass
{
private static IList<string> _directions = new List<string>{"N", "E", "S", "W"};

public static string GetRightTurnDirection(string direction)
{
if (direction == _directions[3]) return _directions[0];

return _directions[_directions.IndexOf(direction) + 1];
}

public static string GetLeftTurnDirection(string direction)
{
if (direction == _directions[0]) return _directions[3];

return _directions[_directions.IndexOf(direction) - 1];
}

public static string GetOppositeDirection(string direction)
{
var directionToTheRight = GetRightTurnDirection(direction);
return GetRightTurnDirection(directionToTheRight);
}
}

The next set of commands we’ll create will allow the robot to turn left and right. This doesn’t change the space the robot is on, only the direction that it is looking.


public class TurnLeftCommand : ICommand
{
private Robot _robot;

public TurnLeftCommand(Robot robot)
{
_robot = robot;
}

public void Execute()
{
_robot.Direction = Compass.GetLeftTurnDirection(_robot.Direction);
}

public void Undo()
{
_robot.Direction = Compass.GetRightTurnDirection(_robot.Direction);
}
}

public class TurnRightCommand : ICommand
{
private Robot _robot;

public TurnRightCommand(Robot robot)
{
_robot = robot;
}

public void Execute()
{
_robot.Direction = Compass.GetRightTurnDirection(_robot.Direction);
}

public void Undo()
{
_robot.Direction = Compass.GetLeftTurnDirection(_robot.Direction);
}
}

Last, let’s take a look at a unit test that puts the robot to work (the source code linked to earlier in the post includes a lot more unit tests if you’re interested in seeing more!).


[TestFixture]
public class When_a_robot_is_given_multiple_commands
{
private Robot _robot;

[SetUp]
public void EstablishContext()
{
_robot = new Robot(new Location(5, 5), "W");
_robot.ExecuteInstruction(new TurnLeftCommand(_robot));
_robot.ExecuteInstruction(new TurnLeftCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new MoveForwardCommand(_robot));
_robot.ExecuteInstruction(new TurnRightCommand(_robot));
}

[Test]
public void Should_end_up_at_the_expected_location()
{
Assert.That(_robot.Position.X, Is.EqualTo(4));
Assert.That(_robot.Position.Y, Is.EqualTo(4)); ;
}

[Test]
public void Should_be_facing_the_expected_direction()
{
Assert.That(_robot.Direction, Is.EqualTo("N"));
}

[Test]
public void Should_be_able_to_undo_the_command()
{
_robot.Reset();
Assert.That(_robot.Position.X, Is.EqualTo(5));
Assert.That(_robot.Position.Y, Is.EqualTo(5));
Assert.That(_robot.Direction, Is.EqualTo("W"));
}
}

Ruby Example

With ruby we won’t need to create an abstraction for our command objects, so we’ll jump right into creating our Robot object. Besides basic syntax differences, this is very similar to our C# implementation.


class Robot
attr_accessor :position, :direction

def initialize(position, direction)
@position = position
@direction = direction
@commands_executed = []
end

def execute_instruction(command)
command.execute
@commands_executed << command
end

def reset
@commands_executed.reverse_each{|x| x.undo}
end
end

It also uses a custom Location class to store X and Y coordinates.


class Location
attr_accessor :x, :y

def initialize(x, y)
@x = x
@y = y
end
end

Next up is the MoveForwardCommand. The @move_action variable contains a hash of Proc objects which contain the logic for moving the robot. Note that we use the “call” method to run the proc.


class MoveForwardCommand
def initialize(robot)
@robot = robot
@move_actions = {:N => Proc.new{|r| r.position.y += 1},
:E => Proc.new{|r| r.position.x += 1},
:S => Proc.new{|r| r.position.y -= 1},
:W => Proc.new{|r| r.position.x -= 1}}
end

def execute
@move_actions[@robot.direction].call @robot
end

def undo
opposite_direction = Compass.get_opposite_direction @robot.direction
@move_actions[opposite_direction].call @robot
end
end

Like our C# example, we make use of a custom Compass class to help find our directions. I really like the explicit “first” and “last” properties that come with the array object, seems to make the code a little easier to read.


class Compass
@directions = [:N, :E, :S, :W]

def self.get_right_turn_direction(direction)
return @directions.first if direction == @directions.last
@directions[@directions.index(direction) + 1]
end

def self.get_left_turn_direction(direction)
return @directions.last if direction == @directions.first
@directions[@directions.index(direction) - 1]
end

def self.get_opposite_direction(direction)
direction_to_the_right = get_right_turn_direction direction
get_right_turn_direction direction_to_the_right
end
end

And our commands to allow the robot to turn left and right.


class TurnLeftCommand
def initialize(robot)
@robot = robot
end

def execute
@robot.direction = Compass.get_left_turn_direction @robot.direction
end

def undo
@robot.direction = Compass.get_right_turn_direction @robot.direction
end
end

class TurnRightCommand
def initialize(robot)
@robot = robot
end

def execute
@robot.direction = Compass.get_right_turn_direction @robot.direction
end

def undo
@robot.direction = Compass.get_left_turn_direction @robot.direction
end
end

Last we’ll take a look at a unit test to that puts the robot through it’s paces. (There are also many more tests in the source code download if you’d like see more examples).


describe "When asked to perform multiple commands" do
before(:each) do
@robot = Robot.new Location.new(5,5), :W
@robot.execute_instruction TurnLeftCommand.new(@robot)
@robot.execute_instruction TurnLeftCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction MoveForwardCommand.new(@robot)
@robot.execute_instruction TurnRightCommand.new(@robot)
end

it "should end up at the expected location" do
@robot.position.x.should == 4
@robot.position.y.should == 4
end

it "should be facing the expected direction" do
@robot.direction.should == :N
end

it "should be able to undo all of the commands" do
@robot.reset
@robot.position.x.should == 5
@robot.position.y.should == 5
@robot.direction.should == :W
end
end

In our next post we’ll take a look at how we can solve the same problem using the State pattern!

kick it on DotNetKicks.com

Share/Save/Bookmark

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

Filed Under (.Net, Ruby) by John Miller on 05-08-2009

Tagged Under : , , ,

Continuing our exploration of design patterns in Ruby and C#, we’re going to dive into the Iterator pattern. Like most design patterns, if you google (or bing) for an example you will run into several different implementations because there are many ways to iterate a collection of objects. In it’s classic (well, classing in the .Net\Java sense) form, the pattern is made of:

  1. An interface defining the iterator. This typically involves two methods: HasNext() and MoveNext().
  2. An concrete iterator implementation
  3. An interface defining an enumerable collection. The only method really needed here would be GetIterator() which will return the iterator object.
  4. A concrete enumerable implementation.

The book Design Patterns in Ruby actually defines that type of implementation as an external iterator. This form gives you a type of hook into the collection that allows you to pull out an object one at a time and work with it externally, away from the insides of the collection. The other type of implementation that it describes is an internal iterator. This form involves a method that passes logic (think anonymous method in C# or code block in Ruby) into a method on the collection. The collection then internally iterates through it’s items and applies the logic on each item. This is a very common way of working with collections in Ruby and is slowly building adoption in C#. As we work through the examples below, we’ll take a look at both external and internal implementations.

The following examples will consist of a used car sales lot which will consist of a collection of vehicles.

C# Example - External Iterator From Scratch

First off, let’s create a basic Vehicle object.


public class Vehicle
{
    public string Name { get; set; }

    public Vehicle(string name)
    {
        Name = name;
    }
}

Our next step is to create an ISimpleIterator interface which we’re going to make generic so we aren’t tied to a specific type of object. It really only needs two methods, HasNext() which will let us know if we’ve reached the end of the collection, and MoveNext() which will return the item in the next position.


public interface ISimpleIterator<T>
{
    bool HasNext();
    T MoveNext();
}

And now we’ll create a concrete implementation of the iterator.


public class SimpleIterator<T> : ISimpleIterator<T>
{
    private int _position = 0;
    private T[] _items;

    public SimpleIterator(T[] items)
    {
        _items = items;
    }

    public bool HasNext()
    {
        return _position < _items.Length;
    }

    public T MoveNext()
    {
        var item = _items[_position];
        _position++;
        return item;
    }
}

Next, let’s create our ISimpleEnumerable interface. We’ll keep this one generic as well since there’s no reason to lock it into only Vehicle objects. Note that it only needs one method that will return a generic ISimpleIterator.


public interface ISimpleEnumerable<T>
{
    ISimpleIterator<T> GetIterator();
}

And our enumerable object will be a SalesLot entity. The GetIterator() method will return a strongly typed vehicle iterator.


public class SalesLot : ISimpleEnumerable<Vehicle>
{
    private Vehicle[] _vehicles = {
                                     new Vehicle("Toyota Camry"),
                                     new Vehicle("Jeep Grand Cherokee"),
                                     new Vehicle("Honda CRV")
                                 };

    public ISimpleIterator<Vehicle> GetIterator()
    {
        return new SimpleIterator<Vehicle>(_vehicles);
    }
}

Let’s see what this code would actually look like if we tried to run it. All we have to do is grab the iterator and wrap it in a while loop.


var salesLot = new SalesLot();
var vehiclesIterator = salesLot.GetIterator();

while (vehiclesIterator.HasNext())
    Console.WriteLine(vehiclesIterator.MoveNext().Name);

Output:

Toyota Camry
Jeep Grand Cherokee
Honda CRV

C# Example - External Iterator Using Built-In IEnumerable Interface

Our design can be hugely simplified by using the IEnumerable interface from the base class library. In the below code sample, our SalesLot object no longer returns an ISimpleIterator, instead it’s passes back a IEnumerator which is also built in the .Net framework. The two GetEnumerator() methods are all that’s needed to fulfill the IEnumerable interface contract. And since all built-in collections implement this interface, we can easily pass that call to the inner list.


public class SalesLot : IEnumerable<Vehicle>
{
    private IEnumerable<Vehicle> _vehicles = new List<Vehicle> {
                                     new Vehicle("Toyota Camry"),
                                     new Vehicle("Jeep Grand Cherokee"),
                                     new Vehicle("Honda CRV")
                                 };

    public IEnumerator<Vehicle> GetEnumerator()
    {
        return _vehicles.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

And using it is just as easy as our earlier example.


var salesLot = new SalesLot();
var enumerator = salesLot.GetEnumerator();

while (enumerator.MoveNext())
    Console.WriteLine(enumerator.Current.Name);

And any class that implements the IEnumerable interface is also able to be iterated over using the foreach construct.


var salesLot = new SalesLot();

foreach (var vehicle in salesLot)
    Console.WriteLine(vehicle.Name); 

C# Example - Adding an Internal Iterator to the SalesLot Class

The previous examples all used external iterators to navigate the collection of cars. But we could have easily used an internal iterator as well. To do this, we need to add a method to the SalesLot object that will allow us to pass in an anonymous method or lambda expression to apply to each vehicle in the collection.


public class SalesLot
{
    private IEnumerable<Vehicle> _vehicles = new List<Vehicle> {
                                     new Vehicle("Toyota Camry"),
                                     new Vehicle("Jeep Grand Cherokee"),
                                     new Vehicle("Honda CRV")
                                 };

    public void ForEach(Action<Vehicle> action)
    {
        foreach (var vehicle in _vehicles)
            action(vehicle);
    }
}

And using it becomes just a couple lines of code.


var salesLot = new SalesLot();
salesLot.ForEach(vehicle => Console.WriteLine(vehicle.Name));

C# Example - Internal Iterator Using the Built-In ForEach List Extension Method

With the addition of Linq, we were given a ForEach extension method on generic lists. Using it is exactly the same as our hand-rolled example.


var salesLot = new List<Vehicle> {
                             new Vehicle("Toyota Camry"),
                             new Vehicle("Jeep Grand Cherokee"),
                             new Vehicle("Honda CRV")
                         };

salesLot.ForEach(vehicle => Console.WriteLine(vehicle.Name));

Ruby Example - External Iterator From Scratch

To get started with our Ruby examples, we’ll create our Vehicle object.


class Vehicle
  attr_accessor :name

  def initialize(name)
    @name = name
  end
end

And since Ruby suports duck-typing, we don’t need to create an abstract class or interface to define our iterator. We just need to make sure it has the appropriate methods. Notice that our functions that return a value (such as has_next or move_next) do not need to include the “return” keyword. In Ruby the last line of a mehod is the return value.


class SimpleIterator
  def initialize(items)
    @items = items
    @position = 0
  end

  def has_next
    @position < @items.length
  end

  def move_next
    item = @items[@position]
    @position += 1
    item
  end
end

We are also free to go ahead with creating the SalesLot class without defining an Enumerable abstraction as long as we include a get_iterator method that returns a SimpleIterator.


class SalesLot
  def initialize
    @vehicles = [Vehicle.new("Toyota Camry"), Vehicle.new("Jeep Grand Cherokee"), Vehicle.new("Honda CRV")]
  end

  def get_iterator
    SimpleIterator.new(@vehicles)
  end
end

Actually using the class is very similiar to the C# example.


sales_lot = SalesLot.new
vehicle_iterator = sales_lot.get_iterator

while vehicle_iterator.has_next
  puts vehicle_iterator.move_next.name
end

Output:

Toyota Camry
Jeep Grand Cherokee
Honda CRV

Ruby Example - Creating an Internal Iterator Using the Enumerable Module

While external iterators have their place, Rubyists tend to favor using internal iterators when working with collections. We could easily tack on our own for_each method to the SalesLot object (as we did in the C# example) but instead let’s jump straight into some of the cool things we can leverage in the library. Ruby ships with a handy module called Enumerable that we can include on our SalesLot object which will give us a lot of functionality for free. To use it, we just need to include the Enumerator module and add an “each” method that accepts a code block.


class SalesLot
  include Enumerable

  def initialize
    @vehicles = [Vehicle.new("Toyota Camry"), Vehicle.new("Jeep Grand Cherokee"), Vehicle.new("Honda CRV")]
  end

  def each(&amp;amp;amp;amp;amp;block)
    @vehicles.each(&amp;amp;amp;amp;amp;block)
  end
end

To be able to take advantage of the features given to us from the Enumerable module, our Vehicle needs to add a method defining the “<=>” comparison operator. This method accepts another Vehicle record to compare to and will return -1, 0, or 1 depending on whether the receiver is less than, equal to, or greater than the vehicle being passed in as an argument. For those of you familiar with the IComparable interface in .Net, this works exactly the same way.


class Vehicle
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def <=>(other)
    @name <=> other.name
  end
end

And now we can iterate through our collection in just a couple of lines.


sales_lot = SalesLot.new
sales_lot.each {|vehicle| puts vehicle.name}

But that’s just the tip of the iceberg. We are given a lot of added functionality that allows us to search and sort vehicles in the sales lot.


sales_lot.include? "Ford Escape"
sales_lot.find_all {|vehicle| vehicle.name.length > 12}
sales_lot.sort

And this functionality is available when working with arrays which allows us to do a lot of work with our collections without having to write much code.


vehicles = [Vehicle.new("Toyota Camry"), Vehicle.new("Jeep Grand Cherokee"), Vehicle.new("Honda CRV")]
vehicles.each {|vehicle| puts vehicle.name}

While the iterator pattern may look complex in it’s natural form, both Ruby and C# give us a lot of capabilities out of the box. Neither need much (if any) customization to do advanced work with collections.

Next time, we’ll check out the Command pattern!

kick it on DotNetKicks.com

Share/Save/Bookmark