image

How do you grade how well an application is written?

There are many factors that will play a role in such an evaluation, for example (in no particular order):

  • Does the design follow object-oriented principles?
  • Does it work? (i.e. few bugs)
  • Does the code have unit tests?
  • Is the code clean (easy to read, small functions)
  • How much code duplication is there?
  • Is there valuable code comments?

Of all those qualities I will have to say readability is the most important quality, I don’t care how procedural the code is so long as the functions are small and the conditional logic written in a such a way that it is easy to follow. Don’t get me wrong I value object-orientation, the S.O.L.I.D principles and unit tests a great deal. But the majority of existing systems I have been tasked to maintain and develop new functions in seldom exhibited any those qualities.

What is usually found is a mess of procedural code where most of the code is located in the codebehind and with some common code moved to static methods on helper classes). 

What constantly surprises me is how competent and intelligent developers can create complex and functioning systems but fail to grasp the simplest of methodologies of writing readable code.

Here is some really bad code which has some of the characteristics that constantly frustrates me:

System.Web.UI.HtmlControls.HtmlInputFile objFile =
  (System.Web.UI.HtmlControls.HtmlInputFile)objControl;

try
{
  if(System.IO.Directory.Exists(strDir)==false ||
     Request["id"] != null && Request["id"] == "1" && isTpActive)
  {
    System.IO.Directory.CreateDirectory(strDir);
    
    MyApp.Business.Entities.Order order = 
      MyApp.DataAccess.Production.GetOrder((int)Request["id"]);
  }
  
}
catch(Exception ex)
{
  error = true;
  MyApp.Business.Logging.ErrorLog.Append(ex);
}

The code above is not real, I actually wrote it just show what I mean. I am having a hard time understanding how people can write code like above. Why include the namespaces in everything? This is something I constantly see and I have never understood the reason for it. Then there are the classics, like complicated conditionals that don't contain any information as what the intent of the condition is. Exception handling is also misunderstood and misused. I often find excessive capturing of exceptions, it’s like try/catch is used like guard clauses, this is very frustrating because it makes debugging and troubleshooting very painful.

Anyway, this post was not supposed to be a rant on bad code but about my realization that readability is the quality that I value most. Sure you get frustrated with procedural code that could have been so much simplified and reduced if some object orientation principles where applied but at least you don’t get a headache when trying to decipher code that is readable :)

image I have spent the last couple of days trying to find ways to parallelize GenArt WPF using Parallel.For (from the Parallel Extensions Library). In the process I stumbled upon a scenario where using Lambdas/anonymous delegates can have pretty substantial performance implications.

The code in question looked something like this:
internal void Mutate(EvolutionContext context)
{
    context.IfMutation(MutationType.AddPoint, () =>
    {
        AddPoint(context);
    });
        
    ///...
}

The function above was called in a while loop until a mutation hit was generated. I was not seeing the CPU utilization I was expecting. I was expecting 100% but got around 80% which I found strange, there was nothing that I could see that would cause a thread lock. To find the cause I started commenting out code. It was when I commented out the code above that I immediately saw the CPU utilization jump 100%. It must have been the garbage collector that caused the decrease in CPU utilization. Why the garbage collector? Well the code above will actually compile to something very different.

Something like this (reconstructed approximation of the generated IL):

public class c__DisplayClass1
{
    public GeneticPolygon __this;
    public EvolutionContext contex;

    public void Mutate__0()
    {
        __this.AddPoint(contex);
    }
}

internal void Mutate(EvolutionContext context)
{
    var lambdaClass = new c__DisplayClass1();
    lambdaClass.__this = this;
    lambdaClass.contex = context;

    context.IfMutation(MutationType.AddPoint, lambdaClass.Mutate__0);
    
    ///...
}

As you see the C# compiler actually creates a separate class to hold the lambda method body, a class that it will be instantiated every time the Mutate method is called. The reason for this is that it needs to capture the local variables (this is was makes lambdas/anonymous delegates true closures). I was well aware that this was happening but I have never encounter a situation where this has had any noticeable performance implications, until now that is.

The fact that lambda methods that use local variables will result in an instantiation of a new object should not be a problem 99% of the time, but as this shows it is worth being aware of because in some cases it can matter a great deal.

imageDeveloper Summit is a great developer conference held in Stockholm each year. This time it is being held in April spread over 3 days with two conference days between 15-16 April and one workshop day on the 17th. I am going to have talk about Dependency Inversion (the pattern/principle) and how this pattern can help you create more loosely coupled applications. The talk will also be about what Inversion of Control containers are good for and how to use them effectively.

I will also host a workshop about test driven development with ASP.NET MVC. A workshop that will be focusing on the testability aspects of ASP.NET MVC. Lab assignments could for example start with an empty controller test. I will go into scenarios where you need to use mocking/stubbing and scenarios where the MVC framework cleverly avoids mocking (by passing FormCollection to the action for example). There is also going to be lab assignments and examples that show how to use WatiN for integration testing.

Other interesting talks:

  • Good Test, Better Code by Scott Bellware
  • A Technical Drilldown into “All Things M” by Brian Loesgen
  • RESTful Enterprise Integration with Atom and AtomPub by Ian Robinson

There are many more interesting talks, so be sure the sign up if you can.

I have been playing with the WPF framework Caliburn and just to have something fun to work on I ported Roger Alsings "EvoLisa" to WPF (from WinForms).

 genArt_WPF

I have preciously ported this app to Direct3D, and to Silverlight, these ports did not work out as I had hoped (although the native C++ Direct3D port was pretty fast). The application UI architecture was inspired by NHibernate Profiler (I took a sneak peek at the code via reflector, I hope ayende don’t mind). It was the fact that NHibernate Profiler uses Caliburn that got me interested in Caliburn in the first place.

To checkout the code (Subversion): http://tlo.googlecode.com/svn/trunk/GenArtWPF/ (This is just a experimental spike to learn wpf/caliburn so no unit tests)