While using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of above in different cases?
Thanks in advance!!
Software Engineering Stack Exchange is a question and answer site for professionals, academics, and students working within the systems development life cycle. It only takes a minute to sign up.
Sign up to join this communityWhile using an 'if' statement to check whether a variable is an empty string or not we can write it in two ways i.e. if('' == $variable) and if($variable == ''). I want to know what is the impact of above in different cases?
Thanks in advance!!
In a modern language, you should be writing your conditions of the form if($variable == "")
. This makes the condition easier to read for natural English speakers.
In a legacy language, it sometimes was considered good practice to use the form if("" == $variable)
as if you used the more natural form it was possible to create compilable and runnable code which was bugged if you accidentally missed one of the '=' symbols.
Now, most compilers, even for these older languages, will at least warn you if you accidentally miss the '=' symbol.
TL;DR; - use if($variable == "")
=
vs. ==
bug is a real concern. But even in Java, if you have boolean
s, both if(a=false)
and if(a==false)
are legal, but the result is different! (And at least my compiler doesn't warn about this case - why would it, because either case is perfectly correct code.) IMO that's a good reason to use if(""==$variable)
exclusively.
Sep 18, 2014 at 6:36
if
conditions, precisely because it's a common source of error. You normally silence the warning by parenthesising the assignment - it's a way to signal to the compiler "yes, I know what I'm doing."
Sep 18, 2014 at 7:00
This highly depends on the language used!
If ==
is implemented as a method in an object oriented language then the construct if ($variable == "")
could lead to an exception because the object ($variable
) might not be initialized or even null
.
If you reverse the expression (if ("" == $variable)
) then you can be sure that the object acted on (""
is always initialized and never null
).
As an example in Java (where the method is called .equals()
):
string.equals("")
can cause a NullPointerException
because the object string
may be null
.
"".equals(string)
cannot lead to a NullPointerException
as the object ""
is never null
.
If ==
is not a method of an object then it does not matter which order is used.
I think that many programmers with such a background use the expression if ("" == $variable)
because they are more familiar with it.
"".equals
. Thanks for the tip :).