Monday, February 18, 2013

Coding in plain English

I've worked on many projects and I've seen my share of code. There is all kinds of coding style going from the most elegant to the "I'm your worst nightmare".

The thing is that "not so elegant code" is often written because of lack of time to do better. Deadlines will force coders to implement some duck tape here and there, while thinking that when they'll have time, they'll make it more elegant and efficient.

That's kind of a wishful thinking process since we all know that going back to change what's already working is a no-no in the business of software developpement.

But some times, there is code that just does not make sense. From a computer point of view, the code works. But from a human perspective, it does not tell the story of the process at all.

Here's an example:


float r = 10f;
while (i < 255){
int c = temp[i] * r / 100f;
temp[i] = c;
i++;
}


Some of you may have guessed that it's a simple calculation to apply an alpha channel based on a ratio. This is a simple example, quite explicit for the initiate. But for a coder who never worked with colours, it will require some effort to understand. The code is clear, the context is not...

Let's re-write that in a more elegant way:

float transparencyRatio = 0.1f;
for (int colorIndex = 0; colorIndex < imgBufferData.length; colorIndex++){
imgBufferData[colorIndex] = imgBufferData[colorIndex] * transparencyRatio;
}


There is a much better way to do that kind of calculation, but I just wanted to illustrate that naming variables, avoiding unnatural operations and ensuring that the code can be described easily in plain English will help everyone, including you, when you'll have to go back in that code section, a few months later.

Another example is when you have to deal with delegate functions. It has the benefit of saving memory and process time but may render the code completely unreadable.

myObject.executeDelegate() is one of the worst line of code to debug. To find out what is the object and what it does, you'll have to debug line-by-line and follow the process to figure out what is going on.

Make sure that the code is explicit enough so that any experienced coders will be able to read it as plain English. Sometimes, we have to implements some twists to make it work. Add comments and try to make you code as clear as possible since it can be tricky to understand.

Finally, avoid multiple conditions in a single IF condition. You know, the kind that you need to split to find out which condition was TRUE and made the execution enter that block... I've seen some IF having to deal with 12 conditions to validate the execution of the code block below... And I'm not even talking about the infamous if not (not(x or y) and (z and x) or not y).

Happy coding!

Patrick Balleux

No comments:

Post a Comment