# Thursday, June 24, 2010

Several years ago, a coworker of mine made a statement that I still consider pretty profound.  To paraphrase, he said that his career goal was, over his lifetime, to delete more code than he wrote.

It’s a simple statement that at the time I thought was a pretty good idea – after all we were about a year into coalescing a whole load of separate code bases into a single one and we’d already done a lot of slashing of redundant stuff.  But the more code I write and the more I think about it, the more I think that his goal is nothing short of software genius that we should all strive to achieve.

I'm going to call the measurement of this goal a developer's Delete-Write Ratio, or DWR, calculated quite simply as [lines deleted]/[lines written].  If you do a lot of deleting, it's going to be > 1.  If you do more writing you're going to have a DWR < 1. 

I imagine that over the span of a career the number is going to start really low as a fresh developer who thinks he knows everything but really knows close to nothing and then creeps up as you gain knowledge. I'm also willing to bet that very few developers ever reach a value of 1.0, so if I achieve even close to a 1.0 DWR I'll be really happy.

Of course when you spend a majority of your time working in an existing code base, it’s usually a lot easier to find “opportunities to delete” than when writing new code.  Since a large amount of what I seem to write is from the ground up it’s difficult to keep my short-term DWR above one.  I’d propose that developers who are primarily writing new code should amend their goal to make it as difficult for the next developer to achieve a DWR above 1 as possible.

What that means is that, as a developer, you need to justify the existence of the code you write.  This doesn’t mean you need to write cryptic code that others can’t read but it does mean that the code you write needs to have purpose.  If two sections of code have the same or similar purpose, then you’re making it easy for someone else to refactor and raise their DWR.

So what can we, as developers trying to make our way through our projects and meet the deadlines foisted upon us?  There are the easy things, like using existing code instead of reinventing the wheel and constantly looking for opportunities to refactor not just existing code but also code as we write but more important is to discipline ourselves.  Don’t give in to schedule pressures that make you think that copying that code file and making a few tweaks will get you toward your goal.  Use inheritance and base classes or refactor to a generic.

Any time you find yourself using copy-and-paste a big red flag should go up.  In fact, I think an awesome Visual Studio add-in that would aid code quality would be something that prevents copying and pasting any more than 2 lines of code at a time.  Seriously, if you are pasting more than a couple of lines of code, it’s very likely that you’ve got an opportunity to refactor.

Even though our lives revolve around the code we write (at least our lives with respect to our jobs), code really is the enemy.  The more code you have, the more bugs you have and the higher your support costs.  Obviously the perfect, utopian-as-unicorns software would be that which meets all of your customers' needs and takes zero lines of code to do so.  Until we figure out how to work that kind of magic, though, we have to settle for less-than-perfect and lay down some code.  But when you're writing that code ask yourself, "what is this doing to my DWR?"

Thursday, June 24, 2010 5:39:39 PM (Central Daylight Time, UTC-05:00)  #     | 
# Monday, June 14, 2010

I just checked in another update to the OpenNETCF.IoC framework.  If you've used the framework for event aggregation you're probably aware that an EventSubscrition can set the ThreadOption to "UserInterface" but that had no effect.  We'll I've fixed that - at least partially.  Up until now I couldn't figure a way to wire up any arbitrary delegate without the availability of Emit. Today I had the idea that implementing a known subset could be done without Emit, but instead hard-coding a class into the framework that handles doing the Invoke call to get the event into the proper context.  Now if your event handler is of type EventHandler or, more importantly, EventHandler<T> (meaning that if you use the GenericEventArgs already present in the framework, you're all set), you don't have to call InvokeRequired and Invoke any longer - the framework handles it for you (and I really wish I'd done that 6 months ago - would've saved me a lot of headache).

Monday, June 14, 2010 6:10:10 PM (Central Daylight Time, UTC-05:00)  #     | 

Microsoft has been very quiet for the past few years with regards to the Windows CE OS and this has lead to quite a bit of speculation about the demise of the OS.  Since the OS is still the underpinning of both Zune and the upcoming Windows Phone 7, it's hard to imagine that the OS is going away but the rumors persist.  It certainly doesn't help that Microsoft was long silent on the matter (and even what they have finally said is pretty nebulous) or that they still haven't given us any clear indication of what the development story is going to be.

One new bright spot that indicates their commitment to the platform as a general embedded offering is their new posting of a job position for an Technical Evangelist for the platform.  This is *not* a position for espousing WinPhone or Zune, but purely Windows CE (or Windows Embedded Compact if you prefer the newer marketing spin).

Maybe this signals a new ramp-up and commitment to us lowly, knuckle-dragger embedded developers.  Once can hope anyway.

Monday, June 14, 2010 12:25:17 PM (Central Daylight Time, UTC-05:00)  #     | 
# Tuesday, June 01, 2010

Microsoft has finally announced the next vesion of Windows CE - renamed (because their marketing team needs something to do I guess) Windows Embedded Compact 7Get the CTP here.

Tuesday, June 01, 2010 8:08:36 AM (Central Daylight Time, UTC-05:00)  #     | 
# Friday, May 28, 2010

Every time we start a new project using our Padarn Web Server, I always like to see if we can improve the server's capabilities to make our job a little easier.  On the last project that turned into adding custom IHttpHandler support so we could easily serve up REST-based web services.

Well we started a new project last week, and unlike the last one, this one is UI-focused (the last one used Padarn strictly for services).  With that in mind, I went about looking at how to improve and simply building pages.

Of course I came back to our lack of support for server controls.  I did a little more playing and decided once again that it's a gigantic amount of work and it requires a boatload of RegEx and string manipulation - not necessarily a recipe for success on a low-memory, slow-CPU Windows CE device.

Still, there had to be other thing that full-blown ASP.NET offers that would be reasonable to add and that would help.  The existing samples we'd created in the past used overrode Page_Load method and then went about doing Response.Writes to emit page code.  The first time I did it I found it painful, so I created a class library that had objects for a lot of the basic HTML constructs and used that to at least help in generating well-formed code.

Still, I didn't really like the object model - it was still way too verbose - and it wasn't really like what anyone does on the desktop.  Additionally, rending in Page_Load really didn't feel right.

So I started looking around and found that the ASP.NET Page class provides a Render method.  That sounds a lot more like where I should be, oh maybe *rendering* a page.  Of course it required implementing the HtmlTextWriter, but that wasn't too terrible.

Once I implemented the Render method and started using the HtmlTextWriter, I quickly concluded that it, too, really sucked for generating page code.  It's just crazy verbose, it doesn't read anything like the page you're attempting to render and it's got things that just feel plain wrong (like having to add attributes before the tag they apply to? WTF is that?).

So I started looking at how ASP.NET developers who render their own controls with this monstrosity got around in.  It turns out that there is a pretty nice fluent interface to the HtmlTextWriter available on CodePlex.  It was missing a lot of stuff that I needed (and had a load of non-HtmlTextWriter stuff I didn't need), but it was a great start.  So after expanding the object model there I can now render a page in something that doesn't give me quite so much heartburn.

What originally looked like this:

protected override void Page_Load(object sender, EventArgs e)
{
  Response.Write(DoctypeTags.XHTML1);

  Response.Write("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
  Response.Write("<head>");
  Response.Write("<link rel=\"stylesheet\" type=\"text/css\" href=\"css/mystyle.css\" />");
  Response.Write("</head>");

  Response.Write("<body>");

  Response.Write("<h1>");
  Response.Write("Hello World!");
  Response.Write("</h1>");

  Response.Write("</body>");
  Response.Write("</html>");
  Response.Flush();
}

Ends up looking more like this:

protected override void Render2(HtmlTextWriter writer)
{
  writer.Write(DoctypeTags.XHTML1);

  writer
    .Tag(HtmlTextWriterTag.Html, t => t["xmlns", "http://www.w3.org/1999/xhtml"])

      .Tag(HtmlTextWriterTag.Head)
        .StylesheetLink("/css/mystyle.css")
      .EndTag() // head

      .Tag(HtmlTextWriterTag.Body)
        .H1("Hello World!")
      .EndTag() // body
    .EndTag(); // html
}

And it gets much cleaner looking the larger the page is.  I also find I'm doing a lot less searching for where I malformed my HTML.

I think the next Item I'll look into is the __doPostBack Javascript method that IIS injects into pretty much every page.  It's probably the next incremental step toward better productivity.

Friday, May 28, 2010 6:43:06 PM (Central Daylight Time, UTC-05:00)  #     | 
# Thursday, May 27, 2010

Introduction

Some time ago I explained to one of my friends the benefits of using GetInvocationList when raising events over simply calling the event handler delegate directly.  He understood my explanation and they implemented their events using the pattern.

Well today he was asked by another engineer why the code is always using "this GetInvocationList call for events" and so I figured I could revisit the explanation a little more formally both for his benefit as well as the other 3 people that read this blog.

The Challenge of Multicast Delegates

An event is, for all intents and purposes, a muticast delegate.  What that means is that you can have 0:n listeners listening for that event.  When you get you call the delegate directly in your code, the CLR iterates through all of the listeners and calls them for you without you having to know how many listeners there are.  This is all well and good *when things go right* but the problem is that things don't always go right.  This is especially the case if you're writing a class that will be consumed by someone else and you have no control over what their handler might be doing.

What happens if a handler throws an exception?  Well the CLR stops iterating through delegates an raises that exception to the method that invoked the delegate.  All handlers that were in the delegate list after the exception *will never see the event*.

To be a little more concrete, let's look at an example.

Let's say we have a class that publishes an event.  We'll call it Publisher and name the event the very original name "MyEvent".

class Publisher
{
  public event EventHandler MyEvent;

  public Publisher()
  {
  }
}

Now when we want to raise that event, the most common thing I've seen is to just get a handler and call it (ensuring it's not null).  Something like this:

public void RaiseDirect()
{
  var handler = MyEvent;
  if (handler == null)
  {
    Console.WriteLine("No listeners");
    return;
  }

  try
  {
    handler(this, null);
  }
  catch(Exception)
  {
    Console.WriteLine("A listener threw an exception in its handler");
  }
}

Now let's look at where this falls down.  First let's create a couple listeners.  Good ones that successfully run an EventHandler and bad ones that throw an exception in their EventHandler:

class Listener
{
  static int m_number = 0;

  public Listener()
  {
    m_number++;
    Name = this.GetType().Name + m_number.ToString();
  }

  public string Name { get; private set; }
}

class GoodListener : Listener
{
  public GoodListener(Publisher publisher)
  {
    publisher.MyEvent += new EventHandler(publisher_MyEvent);
  }

  void publisher_MyEvent(object sender, EventArgs e)
  {
    Console.WriteLine(string.Format("{0} handled event", Name));
  }
}

class BadListener : Listener
{
  public BadListener(Publisher publisher)
  {
    publisher.MyEvent += new EventHandler(publisher_MyEvent);
  }

  void publisher_MyEvent(object sender, EventArgs e)
  {
    Console.WriteLine(string.Format("{0} threw in handler", Name));
    throw new Exception("failure");
  }
}

Now let's wire these up and see what happens with some quick test code:

List<Listener> m_listeners = new List<Listener>();

Publisher publisher = new Publisher();

for (int i = 0; i < 5; i++)
{
  if (i % 3 == 0)
  {
    m_listeners.Add(new BadListener(publisher));
  }
  else
  {
    m_listeners.Add(new GoodListener(publisher));
  }
}

Console.WriteLine("Direct event");
Console.WriteLine("------------");
publisher.RaiseDirect();

We run this and we get the following:

directevent.png

You'll see that only 1 handler (a bad one) ran.  It threw an exception and no one else knew jack about the event.

Using the Invocation List

Now let's look at how we get past this.  The EventHandler delegate exposes a method called GetInvocationList which returns an array of all of the delegates.  Using this we can iterate across all of the EventHandlers manually.  Something like this:

public void RaiseIterative()
{
  var handler = MyEvent;
  if (handler == null)
  {
    Console.WriteLine("No listeners");
    return;
  }

  foreach (EventHandler h in handler.GetInvocationList())
  {
    try
    {
      h(this, null);
    }
    catch(Exception)
    {
      Console.WriteLine("A listener threw an exception in its handler");
    }
  }
}

Now when we run our test code, raising the events through the iterative handling routine, we get this

iteratedevent.png

As you can see, *all* of the EventHandlers ran.

Conclusion

We can't always control the code that other developers write (I'd argue we can't even really control our own code).  If you're writing code that's raising events to be consumed by any handlers (and most events I've seen are meant to be consumed) then you need to think defensively.  How can you protect your consumers from one another's bad behavior?  By coding defensively, that's how.  Simple patterns like calling GetInvocationList is a good defensive strategy.  It not only makes your own code more solid, it prevents those support calls from developers complaining that your assembly isn't raising events, even when they were the root cause.

Get the full source code here: InvocationTest.zip (27.37 KB)

Thursday, May 27, 2010 2:59:54 PM (Central Daylight Time, UTC-05:00)  #     |