Head in the Clouds

The past couple of months have been really fun as we have moved our whole product (lock stock and barrel) out into the Cloud. Along the way I have learned a couple of things about the Cloud and myself that I think (clearly) is enlightening.

Its weird, actually. It seems like I have been going through a renaissance of sorts lately with everything that has been going on. Perhaps it has more to do with the epiphanies and “ah ha” moments as of late but in either case, plenty of topics to cover so let’s not waste any time.

It was about four or five months ago when my boss came up to me and said “We’re dumping our managed hosting provider and moving everything out to Amazon.” After I picked my jaw up off the ground I got a little pain in my gut from the uncertainty of our current product being able to move to the “cloud.” Then it felt like I got kicked in the stomach when he followed up with “I want customers to access it by the end of June.”

At this time I had been with the company for about nine months and had taken over a part of our product that was developed with a very academic SOA approach to the point were nearly everything had to be a web-service (using WCF of course). One solution had 130 projects and zero unit tests.

Needless to say, the current product was not going to work in the Cloud so a re-architecture was needed. Later posts will cover more of the specifics of how this was done/achieved but one thing that sticks out in my mind is our solution for messaging based services.

Initially the thinking was that we would go with NServiceBus out in the Cloud and have these sweet autonomous services with publish/subscribe capabilities and dispatching goodness. This way we could dump the WCF web services, flatten the web applications and have these event-like services.

I was really excited about this opportunity since I had come off of a deep dive with NServiceBus and was already considering a re-architecture of sort when the request to move to the Cloud was made.

As you might have gathered from earlier, the plan was to use Amazon EC2. With my experience in the Cloud being all of nothing, off I went to research and get a handle on this whole Cloud thing. It took all of about ten minutes after bringing up a couple of instances that I found that NServiceBus was not going to be a viable solution (i am still determined to get it working out there).

[Update: It should be noted that the reason behind not using NServiceBus had more to do with the lack of knowledge with the Amazon EC2 than NServiceBus itself. To be fair to NServiceBus...]

With things I learned just from reading up on NServiceBus and reading Udi Dahan’s articles however the decision to move towards an autonomous message based solution for our services was still crystal clear.

So Amazon SQS was used in lieu of MSMQ and “messaging service” windows services were written in lieu of NServiceBus. Granted, the whole publish/subscribe thing is a manual effort and there is no dispatching goodness but that’s not the point.

So what’s the point?

Just because you can’t use a framework or tool set doesn’t mean that you can’t use the principles and ideas behind them. NServiceBus was a “no go” out in Amazon but implementing a messaging based service is still an amazingly strong approach.

Another point that I think applies to the overall experience is that moving to the Cloud doesn’t mean that you have to change the way you think about solutions but rather if you have to make massive changes, modifications, and re-architect your solutions you more than likely didn’t have a very strong one to begin with.

WLW Plugin for WordPress.com – New Version

Almost immediately after I published the WLW WordPress.com Syntax Highlighter to CodePlex a little voice inside my head was telling me that I can do better than that. Luckily for me, that voice was right.

You can find it here: WLW WordPress.com Syntax Highlighter Plugin

The problem with the initial version of the plugin was the fact that I could not get around the "auto-encoding" feature from WLW. This basically meant that any time you wanted to have quotes or angle brackets in your code it would get encoded. Worse still was you had to go to the "Source" tab, correct the encoded characters and then remember to not go back to the "Edit" tab. Sounds like a great plugin to me…

To resolve this issue I switched from using the ContentSource base class to using the SmartContentSource base class. This base class provides you with the ability to have two sets of content: the "Editor" version and the "Publish" version. The "Editor" version is obviously what you see within WLW while the "Publish" version is what is sent to your blog.

Two methods… how simple is that?

Well… when you start off using the ContentSource and WPF… not so simple. The SmartContentSource has what is called an "Editor" which appears in the right pane of WLW when the content is selected. This "Editor" must inherit from SmartContentEditor which in turn inherits from Windows.Forms.UserControl.

Rather than attempting to fight that battle I found it was simpler to just pull out the WPF stuff and go directly with a Forms version.

Funny how the original intent was to show how to create a plugin for WLW using WPF only to rip it out. Live and learn… I guess.

WLW Plugin for WordPress.com on CodePlex

There have been some requests to have me publish the WordPress.com sourcecode highlighter plug-in that I created for Windows Live Writer. So I went ahead and created a CodePlex project for it and published the code and the assembly.

You can find it here: WLW WordPress.com Syntax Highlighter Plugin

There is no official release but you can go to the "Downloads" tab and select the alpha release.

Publishing this out on CodePlex was actually fun and nerve racking at the same time. Since this was the first project that I ever published out there I wanted to make sure that everything was in "tip top shape." I can’t tell you how much time I spent just getting the "summary" correct. I must have rewritten it about five or six times. I am sure I made some faux pas but how is a guy suppose to learn?

Then I realized… it is what it is. Either people are going to find it useful or people are going to think its junk. Either way… it is the spirit of it all that I am finding more interesting. I had a need, wrote a little plug-in to satisfy that need, and am now sharing it to those who are interested.

What I think is going to be even more fun is revisiting this code later and seeing what improvements can be made and how to make it better.

So enjoy and let me know your comments and suggestions.

NServiceBus – Fifteen Minutes…

After downloading the assemblies I was ready to create my first sample application using NServiceBus. From what I can tell, a lot of time and effort has gone into building the NServiceBus.Host executable so if you plan on using it… you’re in luck, there are plenty of examples out there on how to use it. If you don’t want to use it, however, get ready for some digging (take a guess on which direction I went in). Hopefully this post will serve as a good example of how to handle things when you don’t want to use NServiceBus.Host. Time will tell…

The most basic example is sending a message. Note that this is not publishing a message but simply sending a message. To send a message you will need something that sends the message and something that will receive the message. Go ahead and create two console projects: 1) “Sender” and 2) “Receiver”.

You will need to be able to define a message that both the sender and receiver will be able to understand so go ahead and create library project (name it “Messages” for now to keep things simple).

Again, doing the most simple thing possible, add a reference to “NServiceBus.dll” to the “Messages” project. Create a new class, add the “Serializable”  attribute, and have the class implement the “IMessage” interface. This interface is nothing more than a indication to NServiceBus that it can be used as a message. And since we are going to be passing this class around as a message we need to be able to serialize it across the wire so… don’t forget the “Serializable” attribute.

[Serializable]
public class ExampleMessage : IMessage
{
  public int Id { get; set; }
  public string Message { get; set; }
}

A “message” can be thought of as a Data Transfer Object (DTO) in that the message should only contain data and really shouldn’t contain any methods or logic. There can be some interaction with the data like formatting or structuring but avoid putting any logic. Remember that this is going to be serialized.

From here add the “Messages” project as a reference to the “Sender” and “Receiver” console applications. While we are at it, go ahead and add a reference to “NServiceBus.dll” and “NServiceBus.Core.dll”.

Up to now we have three projects: Messages (contains our message class), Sender (the application that will send the message) and, Receiver (the application that will receive the message). So far so good.

The Sender

So now we want the “Sender” application to send a message out into the world. Prior to being able to send a message we first have to instantiate a service bus (for NServiceBus this is an IBus). NServiceBus has a “fluent interface” class named “Configure” that uses an Inversion of Control (IoC) container to build up, configure, and create an instance of a service bus. By default this is done through Spring.Net which is all nice and good but I prefer to use StructureMap so… that is what I choose to use here. The only difference in this example is the “StructureMapBuilder” call which tells NServiceBus to use StructureMap as the IoC container. If you leave this line out… you will use Spring.Net.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
  .CreateBus()
  .Start();

Now we have a service bus that we can send messages with. In order to send a message all we need to do is new up an instance of our class from the “Messages” project and call the Send method from our service bus instance. For this simple example we do this in a while loop where each time we hit “Enter” we send a message:

while (Console.ReadLine() != null)
{
  var message = new ExampleMessage(1, "My First Example");
  bus.Send(message);
}

Finally it is time to configure our “Sender” application. Here we need to add an Application Configuration File (App.config). Since we are sending a message we need to configure our MSMQ Transport and our Unicast Bus.

NOTE: Unlike other configuration sections you cannot “name” the section something different. The following section “names” must be as they appear or they do not work. Not 100% why this is but… if you don’t then it will not work

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MySenderQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
  <UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="">
    <MessageEndpointMappings>
      <add Messages="MessageTypes" Endpoint="MyReceiverQueue" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

Right now the important pieces to cover in the configuration are: InputQueue, Endpoint, and Messages.

InputQueue defines where this service bus can receive messages. Since the “Sender” is never going to receive a message in this example we can safely put anything we want here. For consistency I put “MySenderQueue”.

Endpoint defines where this service bus will send messages. This is a really important setting. We will be using this value later when we configure the “Receiver”.

Messages defines what type of messages this service bus will send to the Endpoint. Here we can break this up to be type specific but for this example we will simply instruct the service bus to send all of the messages from our “Messages” project to the Endpoint.

The Receiver

Now we want the “Receiver” to receive messages from the world. Prior to being able to receive messages we first have to instantiate another service bus similar to the way we did in our “Sender” project. The only real big difference in configuring this service bus is telling NServiceBus to load in our message handlers.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
    .LoadMessageHandlers()
  .CreateBus()
  .Start();

Since we don’t want our “Receiver” application closing as soon as we bring it up we need to add a little bit of code to make sure it sticks around while we test:

Console.ReadLine();

If you notice the only difference between the “Sender” and the “Receiver” is the LoadMessageHandlers call. So in order for NServiceBus to load our message handlers… we need to have a message handler. To do this simply add a new class and implement the “IHandleMessages<>” interface:

public class ExampleMessageHandler : IHandleMessages<examplemessage>
{
  public void Handle(ExampleMessage message)
  {
    Console.WriteLine("I got an example message... now what?");
  }
}

Finally it is time to configure our “Receiver” application. Here we need to add an Application Configuration File (App.config). Since we are only receiving messages we only need to configure our MSMQ Transport (no need to configure the Unicast Bus).

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MyReceiverQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />

In order to receive messages properly we need to make sure that the InputQueue value is the same as the Endpoint value from the “Sender” configuration. For this example it is “MyReceiverQueue”.

Done

Now you are ready to go and start sending messages from the “Sender” to the “Receiver”.

To do so simply right click the “Sender” project and click “Start new instance” from the “Debug” submenu. After this console app is up and running right click the “Receiver” project and click “Start new instance” from the “Debug” submenu. With both console applications up and running hit “Enter” from the “Sender” window and watch the message appear in the “Receiver” window.

Summary

All and all I would say that this took about fifteen to twenty minutes to get setup and running. That is pretty impressive especially when you start digging into what is actually happening in the background.

In future posts we can go over Publish and Subscribe, Request and Reply, and talk about the Distributor (which is some really neat stuff).

SOLID – Liskov Substitution Principle (LSP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and principles are still strong.

So let’s take a look at one of the principles in SOLID; Liskov Substitution Principle (LSP)

LSP states:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T

Right, to many this is as clear as mud. It took me a while to understand what this principle was really talking about at first. Then after reading a few papers written on the subject it became a little more clear. What I have seen many developers do, however, is paraphrase this principle (or actually rewrite it) to make it easier to understand.

Commonly, LSP is paraphrased to state:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it

So really all we are talking about is making sure our methods use base classes or interfaces as parameters and that the method does not have to know about all of the derived types of the base class or the classes that implement an interface.

Perhaps it is best to use an example to better explain what this principle is talking about.

public class Customer {
  ...
}

public class Vendor : Customer {
  ...
}

public class CustomerValidator {
  public void Validate(Customer customer) {
    if (string.IsNullOrEmpty(customer.Name)) {
      /// indicate that validation has failed
    }
    var vendor = customer as Vendor;
    if (vendor != null) {
      /// we know we are dealing with a Vendor
      /// validate Vendor rules
    }
}

Here we have a Customer class and a Vendor class which inherits from Customer. In the CustomerValidator class we are correctly using the Customer class (which would allow a Customer or Vendor object to be used… good so far) but then the Validate method has to know about the Vendor type and therefore violates LSP. What we can also (hopefully) see here is that we are violating the Open Closed Principle (OCP) due to the fact that any time we create another derived type from Customer we must modify the Validate method to handle the new type (hence it is closed for extension and is open for modification).

So how do we correct the above to remove the LSP violation?

The following is one way (and probably not the best way) to resolve the issues.

public class Validator {
  private readonly IList<string> errors;

  public Validator() {
    this.errors = new List<string>();
  }

  public void Validate(IValidation validation) {
    validation.Validate(errors);
  }
}

public interface IValidation {
  void Validate(IList<string> errors);
}

public CustomerValidation : IValidation {
  private readonly Customer customer;

  public CustomerValidation(Customer customer) {
    this.customer = customer;
  }

  public virtual void Validate(IList<string> errors) {
    /// if we fail validation add an error to the collection
  }
}

public VendorValidation : CustomerValidation {
  private readonly Vendor vendor;

  public VendorValidation(Vendor vendor)
    : base(vendor) {
    this.vendor = vendor;
  }

  public override void Validate(IList<string> errors) {
    /// call the Customer validation routines
    base.Validate(errors);
    /// if we fail validation add an error to the collection
  }
}

Wow. We have changed things up a lot.

If we look at the Validator class we can see that the Validate method takes a parameter which allows us to pass in any class that implements the IValidation interface. This follows LSP because we can substitute any class which implements this interface without changing the behavior. Not only that but the method doesn’t need to know anything about the types which implement the interface. At the same time, we have also solved our OCP violation by making the CustomerValidation class open for extension and closed for modification.

One more important thing that I would like to point out that sometimes get left out when explaining LSP is that exceptions should (or must) follow the same rules. This means that if you are throwing an exception in a method of a base class then any derived type overriding the method should throw the same type of exception. By doing this you can be ensured that your error handling for the base class will be correct for derived types as well. Just something that you should keep in mind.

SOLID – Open Closed Principle (OCP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and principles are still strong.

So let’s take a look at one of the principles in SOLID; Open Closed Principle (OCP)

OCP simply states:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

In my mind following this principle is not limited to inheriting from a base class and marking methods and properties as virtual. While I do believe that there is a time and a place for following OCP in this manner I feel that this is sometimes the only solution that developers think of when thinking about OCP.

Take the following example of following OCP through inheritance.

public class OrderService {
  private readonly IRepository<Order> repo;

  public OrderService(IRepository<Order> repo) {
    this.repo = repo;
  }

  public virtual void Save(Order order) {
    repo.Save(order);
  }
}

public class EmailOrderService : OrderService {
  private readonly ISmptService emailService;

  public EmailOrderService(IRepository<Order> repo, ISmptService emailService)
    : base(repo) {
    this.emailService = emailService;
  }

  public override void Save(Order order) {
    base.Save(order);
    emailService.SendNotification(order);
  }
}

Ok so now we have these classes and we are clearly following OCP but I believe that there is an alternative through use of the Strategy pattern which would make this a little cleaner.

public class OrderService {
    private readonly IRepository<Order> repo;

    public OrderService(IRepository<Order> repo) {
        this.repo = repo;
    }

    public void Save(Order order) {
        repo.Save(order);
    }

    public void Save(Order order, IOrderStrategy strategy) {
        this.Save(order);
        strategy.Process(order);
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    private readonly ISmptService emailService;

    public EmailOrderStrategy(ISmptService emailService) {
        this.emailService = emailService;
    }

    public void Process (Order order) {
        emailService.SendNotification(order);
    }
}

Here we can see that OCP is still being followed since the OrderService class is still open for extension via the IOrderStrategy and is closed for modification. We don’t need to mark any methods as virtual and don’t need to inherit from the OrderService class. What is even better is that we could have implemented a Specification pattern along with the Strategy pattern and really get cooking.

public class OrderService {
    ...
    public void Save(Order order, IEnumerable<IOrderStrategy> strategies) {
        this.Save(order);
        foreach (var strategy in strategies) {
            if (strategy.CanProcess(order))
                strategy.Process(order);
        }
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    ...
    public bool CanProcess(Order order) {
        return order.SendEmail;
    }
    ...
}

So I guess all this really means is that OCP shouldn’t only be thought of as marking methods and properties as virtual. OCP should be thought about and reasoned about a little more deeply and carefully.

And granted the examples given here have holes and are more than likely not the best code you have ever seen but it is the ideas these examples show that should be taken.

SOLID – Single Responsibility Principle (SRP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and the principles are still strong.

So let’s take a look at one of the principles in SOLID; Single Responsibility Principle (SRP)

SRP simply states:

There should be one and only one reason for a class to change

Um… yeah! That makes sense… I guess

So what types of change are we really talking about when dealing with SRP?

This is a question that I have always had trouble answering for two reasons: 1) didn’t really understand SRP to begin with and 2) my focus was always in the wrong area. I have always understood SRP through examples of classes that violated SRP in that it would take someone to state that a given class was violating SRP and why. Then I would simply remember that pattern or example and avoid it rather than taking the time to learn what it meant. When I started taking the time to learn it and gain a better understanding I started to take things too literal. (If I needed to change a method in a class was that violating SRP?)

What I started to do was to think about things as a whole. In other words, while “change” is a very important word in the definition of SRP, the word “class” was what I was missing. When I finally took the word “class” into context… I had my “ah ha” moment (it was really like a “duh” moment).

Ah ha…!

Ok, great. So what does that mean?

The word “class” is a little tricky beast that can mean so many things to different people at different times that I feel it losses it’s importance. Case in point, I find my self interchanging the word “object” with “class” as in “new up a StringBuilder class.” While I don’t think that I will ever stop doing that or stop using the word “class” in my everyday vernacular, I think that word “class” in terms of SRP needs to be changed to “concern.”

So I started to take the common (or the one most popularized) definition of SRP and replace “class” with “concern”:

There should be one and only one reason for a concern to change

Wait for it… ah ha! By making this contextual change I started to realize that my classes needed to be responsible for a single concern.

Now I could start looking at classes in terms of their concern. Thinking about a class that dealt with a Customer object and it’s database interactions became a concern. And with that thinking I realized that the class had one responsibility, interacting with the database for the Customer object. So now the only reason for the class to change was to change the way the Customer object interacted with the database.

WLW Plugin for WordPress.com – Part 1

As stated in my previous post, I have been looking for a plug-in for WLW that would allow me to take advantage of the built in source code highlighter that is available from WordPress.com (the free on-line version). Not being able to find one I decided to write one for myself.

Not knowing where to begin or how to start, I searched for how to build a plug-in for WLW and came across Rick Strahl’s post about creating a WLW plug-in using WPF and decided to do a similar thing. I was fairly confident in my abilities to write a little WPF app but knew nothing about the WLW plug-in architecture so I started there.

For what I needed to do, writing a plug-in was actually really straight forward. I simply added a reference to the “WindowsLive.Writer.Api” assembly, created a class and inherited from the ContentSource class (which inherits from the WriterPlugin class). Looking at the ContentSource class I found that there were three virtual methods that I could choose from: 1) CreateContent, 2) CreateContentFromLiveClipboard, and 3) CreateContentFromUrl. Not knowing what any of these methods did, I choose to override the CreateContent method.

using System;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

namespace SourceCodePlugin {
  public class Plugin : ContentSource {
    public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content) {
      return DialogResult.OK;
    }
  }
}

Now knowing that I could create a WLW plug-in I thought about what I wanted the plug-in to do and how it was going to act. In really basic terms, I wanted to wrap what ever “code” I wrote with “[ sourcecode language="csharp" ]<–code–>[ /sourcecode ]” as the WordPress.com site had suggested.

Thinking about it a little more, I wanted to ensure that the “code” appeared exactly the way I entered it so… it was clear that I needed to wrap the whole thing with “<pre></pre>” tags. So I wrote a little method to do just that.

public class Plugin : ContentSource {
  ...
  private string FormatOutput(string language, string code) {
    var builder = new StringBuilder();
    builder.AppendLine("&lt;pre&gt;");
    builder.AppendFormat("[ sourcecode language=\"{0}\" ]{1}[ /sourcecode ]",
      language, code);
    builder.AppendLine();
    builder.AppendLine("&lt;/pre&gt;");
    return builder.ToString();
  }
}

I decided to give that a shot so I built the project, deployed the assembly to my “Plugins” folder and started Windows Live Writer.

Sure enough… it didn’t work. I totally forgot about the two attributes that you need to add to your class in order for WLW to load your plug-in. Referencing back to Rick’s post I also realized that I should create an image to make it look like all of the others.

[WriterPlugin(
  "9EDA38F6-AE13-4003-B74A-83E8474F528D", 
  "Wordpress Sourcecode Plugin",
  Description = "A [sourcecode] plugin for Wordpress.com blogs",
  PublisherUrl = "http://meisinger2.wordpress.com/",
  ImagePath = "Images.SourceCode.png",
  HasEditableOptions = false)]
[InsertableContentSource("Wordpress Sourcecode Plugin")]
public class Plugin : ContentSource {
  ...
}

After adding that and building it again, sure enough I had my “Hello World” code getting inserted into WLW through my plug-in

Next steps… integrating WPF

Edit: It appears that WordPress.com “sourcecode” bracket magic is a little too good… I had to edit this post and put a space between the bracket (“[" and "]“) and the word “sourcecode” in order for it to come up propertly

Windows Live Writer Plugin for WordPress.com [sourcecode] Highlighter

Recently been wanting to blog more and more about code and give my posts some more punch by providing some code samples. The one thing that I always notice about other blog posts were the nice little syntax highlight boxes for code. You know the one that has the line numbers and allows you to copy to the clipboard or print.

So I set out to get my hands on a syntax highlight plugin that I could use and found a lot of them out there are really neat and well put together. One of the really important things for me was to also find a plugin for Windows Live Writer (which is simply one of the best tools). So long story short, I found my plugin’s and was ready to go.

One small problem, I am blogging on WordPress.com.

So that means, no pluggin directory, no JavaScript files, nothing. I did some reading on the WordPress.com website and found out that they do have and support a syntax highlighter for code. Wow… this was great. Now the only thing left was to find a plugin for Windows Live Writer that would work with this type of syntax highlighter.

If you try to search the web for “Syntax Highlighter”, “WordPress”, “Windows Live Writer”, and “Plugin” you will be presented with hundreds and hundreds of results. All of them talking about something that I couldn’t use, didn’t have, or didn’t want. I was really sad.

I came across a post by Rick Strahl covering some work he did on an Amazon book plugin for WLW using WPF and decided to rollup my sleeves and write my own. I mean think about it… writing a WLW plugin in WPF for a syntax highlighter that hasn’t been made yet (as far as I know anyway)… how cool is that!

So the next few posts will cover what I did to create the plugin and the issues that I ran into while creating it. And before I forget… I need to show of my plugin… The following code snippet was added using the plugin (of course) and shows one of the classes I created for the plugin. It is simply a name/value pair class that I use for the languages drop down list

public class SourceCodeLanguage
{
  private readonly string name;
  private readonly string value;

  public string Name
  {
    get { return name; }
  }

  public string Value
  {
    get { return value; }
  }

  public SourceCodeLanguage(string name, string value)
  {
    this.name = name;
    this.value = value;
  }
}

How cool is that? Well, maybe it isn’t something to write home about but… nah… it is. Currently the list of features this plugin has is really small. I really wanted to get it up and running and prove to myself that I could do it before getting into too many bells and whistles. Features:

  • Selectable indent size (2, 4, 6)
  • Changing the indent size re-formats the “code” sample
  • Selectable “code” language (e.g. C#, Ruby, Python, etc..)
  • All languages supported by WordPress.com are available

Better Unit Testing and TDD

I just got done watching Rob Conery’s latest installment in his Kona series. I have to say that I like the direction that he is going with it and I hope that he continues producing great screen casts.

After watching the video, however, I noticed some of the comments that were made by others and started to get really frustrated over how developers view unit testing and practicing TDD.

I am not saying that I am the end-all-be-all when it comes to unit testing and TDD. Far from it… lord knows that I have worked on projects where I didn’t produce a single unit test and instead relied on firing up a browser and stepping through the application to "test" the code.

I guess the thing that frustrates me the most is when a developer decides to start practicing TDD or they decide that there is enough benefit from writing unit tests only to later throw their hands up in disgust and (understandably) frustration when it is not working the way they thought it would or how some other blogger showed them how easy it was to write unit tests and practice TDD.

It is my belief that most books, articles, screen casts, blog posts, etc… about unit testing and TDD take the wrong approach. Sure, it would be totally awesome if we could all be put on "green field" projects and new code bases where we are starting from scratch. The reality is, however, that most of us are brought on to existing projects and existing code bases where no testing has been done or if it has… it has been abandoned.

So what is a developer to do? The answer is really simple… write unit tests and start practicing TDD.

The one part of Rob’s screen cast that I liked was when he (quickly) covered the unit tests that he wrote for the existing Shopping Cart application. While I wish he would have spent a little more time on it, I think that he really hit on what a developer should be doing when trying to write unit tests and performing TDD on an existing code base.

Start from the Story and Requirements

The point of the matter is that if you start from the story, requirements, or business case then you can start to get a clearer understanding of what it is that needs to be tested and where to start (regardless of if this a green field project or an existing code base).

Some times you might get stuck and not know where to start even after gathering the requirements or reading the stories. This is a clear indication that you don’t know the full story in which case you have a couple of options: 1) assume that you know what is going on or 2) ask. I think where a lot of people get into trouble is when they start assuming things.

Assumptions – How bad Tests start

Let’s watch what happens when you assume (besides the age old saying of making an ass out of you and me).

You receive (or you read) a story which states "the Company [object] must have the ability to add a User [object]" and you go off and write the following code:

[Test]
public void When_Adding_User_UserCount_Is_1() {
var customer = new Customer();
var user = new User();

customer.AddUser(user);

Assert.AreEqual(1, customer.UserCount);
}

 

After you fix the compile errors, etc… you run the test and it fails since you have not implemented the AddUser method yet. So you then start to implement the method and you assume that you are going to store the User in a collection. You then further assume that you are going to want to retrieve the User so you decide to create a Dictionary. You make another assumption that the Id property from the User will be used as the key for the Dictionary. Remembering that you still have to satisfy the test, you change the UserCount property to return the count from the Dictionary. Then finally… you make one last assumption, the GetUser method. You write and implement the GetUser method to take an Integer and return the User object from the Dictionary. Just to be safe, you write a test to prove that after you add the User, you can get the User from the Company object.

Assumptions – So what went wrong?

So what went wrong here? Everything works and all of your tests pass so… what is the deal?

The assumptions are the deal. First you have assumed that you need to store the User in a collection. Nothing about the story or requirement indicated that this needed to be done. After that assumption comes all of the other decisions that were not warranted. Finally the big nasty assumption that the User will need to be retrieved and the API created to accomplish it.

With all of those assumptions made, you have coded and unit tested yourself and every other developer on your team (present and future) into a corner. Not only is there no need to have a GetUser method at this time but you run the risk of the method becoming "supported" because other developers now use it to get User objects.

What is worst of all is that there is code now available that isn’t backed by a story or requirement.

Conclusion

So back to my original point. Writing unit tests and practicing TDD is not as hard as people make it out to be as long as you follow the stories and requirements and don’t make assumptions.

Perhaps that is wrong to state. Assumptions are fine when you are assuming how something will work like how the Customer object will be reconstituted from a database some where. The details aren’t important but it is safe to assume that there will be some data access method some where in the framework or code that will handle the retrieval of the Customer object for you. Other assumptions that are integration assumptions are also fine since the details have more than likely not been ironed out yet.

Assumptions about the test and the functionality needed for the application, however, are bad

Follow

Get every new post delivered to your Inbox.