Att Trejder and inverse boolean tests

In this comment:

http://www.yiiframew…n/config/#c2262

Trejder writes:

I wanted to comment on the comment, but I thought I’d just post it here. :)

That’s a very good coding practice!

I tend to forget it constantly - mainly due to the fact that it just feels very unnatural - but it’s awesome because it is not possible to accidentally assign something.

This would pass but accidentally change the variable:


if($cache = false)

This wouldn’t:


if(false = $cache)

So, it’s a good practice. IMO. ;)

It’s easier to shoot yourself if you don’t use this inverse test technique, if you use non-strict comparison operators, like ‘==’.

Late at night, it’s hard to spot the difference between ‘==’ and ‘=’ …

The technique above is a better-safe-than-sorry approach.

Forgot to mention the rationale:

Put the constant on the right hand side.

Since you can’t assign to a constant, it will fail if you accidentally write ‘=’ instead of ‘==’. ;)

It’s awful to write




if ($var == true) { ... }



instead of




if ($var) { ... }



IMHO of course…

That really depends on how $var is initialized and what type it is.

I tend to use the if($var) form myself - but sometimes it bites you in the rear.

And if you are comparing it as a boolean, empty/non-empty or other type/constant.

IMO.;)

I’m mainly using this style… it comes handy with other data comparison… not too much with boolean…

but for example


if(null==$var)

or


if(10==$var)

or


if(User::STATUS_ADMIN==$user)

You could at least PM my, jacmoe, that you are opening discussion upon my comment! You are a bad boy! :P

No, it’s not! :) All you need is a good software for editing your PHP files. For example using NetBeans (wonderful, but a bit slow!) you will always get green underline in such situations. In this particular, with comment saying “Possible accidental assignment. Assignments in conditions should be avoided”. Brilliant! :)

Also ZendStudio… :P

With the little difference, that Zend Studio isn’t free, am I right? :]

right :D