Hacker Timesnew | past | comments | ask | show | jobs | submitlogin

It's amazing how following good coding standards can make bugs go away. If anyone disagrees, I would suggest reading Joel Spolsky's article "Making Wrong Code Look Wrong": http://www.joelonsoftware.com/articles/Wrong.html That article changed my perspective on coding standards.

To your PSA, I would like to add: Never use the '!' operator at the beginning of a conditional. It's too easy to miss when reviewing or changing code, especially next to certain characters:

    if(!llama) {
        ...
    }
This is a tiny bit more text, and so much safer for maintainers:

    if(llama == false) {
        ...
    }


Now you have the bug occur if someone forgets an equal since this is always true:

    if (llama = false)
So use Yoda conditionals instead:

    if (false == llama)
Is that really an improvement over the original? As I've stated in my sibling reply, you are decreasing human readability for machine readability.


I have seen code that uses the Yoda style, but I think it's a bit overkill. Any C/C++ compiler I've used in the last several years will complain if you do an assignment in a conditional. (Unfortunately I've also seen projects that spew out a slew of compiler warnings under normal circumstances, so YMMV.)


Maybe

    if (llama != true)
instead?

Or maybe you just use a not function:

    if (not(llama))


Sigh... I know of at least one coding standard that insists on not having bare Booleans in conditionals but instead code of this sort:

if (foo == true && bar == false) ...

and it's so prolix it drives me crazy (especially if combined with a naming convention for Booleans, so it's obvious from the name that the value in question is Boolean). I feel like I'm in an epistemology class. "If the truth-value of the proposition p is true...."

If ! is easy to overlook, what about other unary operators? Perhaps we should write (0 - x) instead of -x, (0xffff ^ x) instead of ~x, and x[0] instead of *x.


I've taken to trying to make the ! stand out more:

  if( ! llama) {
          ...
      }
I don't know that it's an improvement, and my personal jury is still out, but I currently hold that it's better than the risk of the single equals bug that another reply points out, or the Yoda conditional that is the suggested replacement.


I think the '!' is easy to spot when using a good monospaced font.


If you're having issues seeing the '!' you have a terrible font and/or syntax color theme.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: