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!!
7
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 == "")
4
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.
1