Variable comparison

From time to time I bounce into a code like:

if ('vodka' == drink.type && 40 == drink.spiritAmount) then {...}

Some people consider it’s a good programming style and that it should supposedly prevent the noobies’ error with accidental variable assignment. No it’s actually not. The good programming style is when your code can be understood not only by a compiler, but by another human. Humans, you know, build the sentences using the normal order: “If the bottle says ‘Vodka’ but amount of spirit is not 40% then it’s a fake”. Okay? Find me someone who normally says something like “If the 161 is a train number that you’ve seen on the ‘arrived’ screen then it’s time to board”.

Besides, if you use this reverse-style with the equality operator, you should probably use it with all other comparison operators, wouldn’t you? That is to write if (10 <= number_of_entries) and so on. So in order to fight one small lame error, which happens once in a year you’re gonna pervert human’s mind and ask smart people to think in a reversed way. I think it’s not worth it.

You wanna fight this error? Fine. Write a pre-commit hook that will execute regex-search and just stop the commit if it finds this bug. There is absolutely zero reasons for a single equation to appear inside the “if (…)” brackets. But please stop messing around with human’s mind. Programmers have better things to remember.

Of course if you join the project and there are already code conventions which claim this style, you must follow them no matter do you like them or not. Or if you build your application on top of an opensource framework that follows that style.

But when I create a new application, I personally choose not to use it.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.