What has you here today?    work history (html) about me tajik bookmarks

17th of September, 2003 ANTE·MERIDIEM 10:25

Okay, in a loosely typed language like PHP or, God forbid, Perl, consider the following snippet;
if ($instanceOfSillyClass->getFlag() == true) { ...

Now, what’s wrong with this? Well, okay, presumably getFlag(), given its name, is going to return something that will make sense in the context of an if  statement test. Let’s go check ... it does, so that comparison with “== true” is redundant. Given our language is interpreted (most loosely typed ones are, today) there’s going to be some—really miniscule—extra amount of time and space needed to parse it, so that’s bad. Not bad to the extent that anyone reading the code will care, though, so it’s okay.

The thing is, there is more to it than that. If someone who does this for a living reads code that is at first sight redundant, that person will ask themselves why that code was written, is there is more to it than what is seen here. And the only reasonable motivation for putting that check there is if getFlag() can return something that would be interpreted as success by an if statement, but that wouldn’t “==” successfully against true. That is, something like:
...
return (count($this->someMemberArray) ? count($this->someMemberArray) :
($otherMember ? false : true));

But getFlag() doesn’t. Okay, right, this looks like a stylistic quirk of our writer. But how will she write the code if she is  using a function that does behave like our second snippet? We can’t be sure, but the first snippet would remain a valid approach, so we have to consider this as likely. So, when our reader sees the “== true”, there is never any certainty of the behaviour of the function result being compared. Not a huge issue, you would imagine. But, there are already enough stupid things that can go wrong when you’re writing code that adding something else decreases our quality of life and tilts the reader’s opinion of you towards the “net benefit to my existence: negative” side of things. So don’t do that, please.

Also, and on an almost unrelated note, - -$kudos to the otherwise cool Larry Wall for removing the option of single-statement blocks for if  {} and for  {} in Perl, just as editors were available that knew enough about the languages to hand that they pointed out cockups in this area early. Thus predestinating people from certain C schools to syntax cock-ups every time they do a short-term venture into the world of non-context-free-grammar and crazy object-orientation syntax.

 [No extant comments for this entry.]

Comments are currently disabled.