Blog Closed

This blog has moved to Github. This page will not be updated and is not open for comments. Please go to the new site for updated content.

Wednesday, February 10, 2010

So Bad It's Funny

At work I've been taking a program written by another engineer and trying to merge the functionality into a program that I've been writing. During this process, I have found some code so bad that it's both funny and depressing at the same time. Here is a great example:
[Update 10 Feb 2010: This code is C#]

public bool CheckMsgValid(byte[] _myArray, int _myIdx) {
bool t;
t = ((_myArray[_myIdx] & 0x80) == 0x80) ? true : false;
return t;
}

...which is basically the long way to write:

public bool CheckMsgValid(byte[] b, int x) {
return b[x] & 0x80 != 0 ;
}

I guess the original coder wanted to make double-sure that the two values were equal.

7 comments:

  1. erm, not this?
    return b[x] & 0x80;

    ReplyDelete
  2. I should have mentioned, the code above was C#, not C. Because of the increased type safety, just "b[x] & 0x80" wouldn't return a bool.

    ReplyDelete
  3. So what does _myArray[_myIdx] & 0x80 mean in C# and why is it superfluous in your code? I thought it was some bit masking.

    ReplyDelete
  4. It is bitmasking. Then the "==" compares the mask and produces a bool.

    ReplyDelete
  5. I'm puzzled. Suppose in b[x] the value 129 (0x81) is stored. What are the results of both functions?

    ReplyDelete
  6. Ah, you're right. I had a typo above. Fixed.

    ReplyDelete
  7. In the meantime I installed a C# compiler on my linux box. And it wasn't happy with that either. Maybe: return (b[x] & 0x80) != 0 ;

    ReplyDelete

Note: Only a member of this blog may post a comment.