Tuesday, April 25, 2006

Programming tip

I had to perform a particular task today, one which I have had to do several times before. I thought I would share it. I'm not sure if you guys all already know how to do this, but here goes.

public int DoSomeWork(int a, int b)
{
return a * b / 2;
}

What we need to do is change the method, so that we can pass a value to divide by, instead of just dividing by two. The catch is that we have several classes, spread across multiple projects and multiple solutions, that all call this method. The chance of missing a call to this method in a different solution is pretty high in this case. How do you make the change without breaking existing code? Here's my technique, which I have implemented at least two dozen times in the app I worked on from 1/05 to 5/06.

public int DoSomeWork(int a, int b)
{
return DoSomeWork(a, b, 2);
}

public int DoSomeWork(int a, int b, int c)
{
return a * b / c;
}

Now, all existing calls all work properly, using the default value that was originally hard-coded. In addition, we can now take advantage of the new functionality going forward. I have found, in my experience, that we generally add a boolean to the method signature, and have an if statement that triggers on that boolean. It works for any type of parameter, though.

Hope this helps you guys.

No comments: