# Monday, 30 June 2008

Justin Etheredge made an interesting point about code readability. He asks us to compare these two functions:

public static int GetNextSize(int i)
  {
    //multiply it by four and make sure it is positive
    return i > 0 ? i << 2 : ~(i << 2) + 1;
  }
 
public static int GetNextSize(int i)
  {
    return Math.Abs(i * 4);  
  }

They do the same thing. One might be faster to execute if there was no such thing as an optimizer. But bit twiddling is notoriously hard to read and maintain. In the comments you can see people saying "don't those two actually return different values?" And that's really his point. Human beings have to read your code and maintain it. They have to understand it. And if you pre-optimize, if you decide that bit shifting is faster than multiplying, you make like harder for everyone after you. Since that might include you yourself, a few years from now, think twice about it. Write readable code. Let optimizers optimize. People time is way more expensive than CPU time.

Some folks think this is a good rule for staff, but that consultants who charge by the hour should go with the clever code. Generally they have two reasons for this. First, they worry that if they write the simple code, someone will look at it and ask "how much an hour did I pay for that!?!?!".  I don't fuss about that, I just think "one dollar for hitting it with a hammer...". Second, they look forward to being brought back every time any changes need to be made to that code, since they're the only ones who understand it. I think that's shortsighted. Once the client realizes you've done that, you'll never get to work on any new projects for them. I'd rather work on a steady stream of new stuff than be stuck bugfixing old stuff for people who resent that I tricked them with my cleverness. And when I do have bugfixing to do, I appreciate being able to read what I wrote :-).

Kate

Monday, 30 June 2008 09:57:31 (Eastern Daylight Time, UTC-04:00)  #