Tuesday, March 8, 2011

Let the compiler do the work

If you have data that can be transposed it will surely be.

Look Mizuho, Instead of selling 1 share  at ¥610,000, they sold 610,000 shares at ¥1 each.

A function that takes two parameters CalculateArea(double length, double width) will eventually be called with width and length. In this case, for most geometries that we care about, no harm done.

But what about some process function like :

void AddDilutedAcid(double ml, double PartsPerMillion)?

The following will compile, run, and cause all sorts of problems.

void MixUpDangerousChemical()
{
     double ml = getVolumeToAdd();
     double ppm = getConcentration();
     AddDilutedAcid(ppm, ml); // Nicely transposed. Should be ml, ppm
}

It would be nice to find that bug at compile time, not at runtime.

What if we had a simple Concentration class. At it's simplest, it would just contain and expose a double.



 public class Concentration{
     public double ppm {get;set;}
}



void AddDilutedAcid(double ml, Concentration PartsPerMillion) {...}

void MixUpDangerousChemical()
{
     double ml = getVolumeToAdd();
     Concentration ppm = getConcentration();
     AddDilutedAcid(ppm, ml); // This throws a compiler error now !!
}

Let the compiler do the work. It always pay attention. Always.

No comments:

Post a Comment