Right from the early days of our programming, we used to write comparison statements like this:
if (myAge == 23) {Use the following style instead:
// Some code
}
if (23 == myAge) {
// Some code
}
This style of coding is valid and has the same semantic as that of the above one. The second form is safer when compared to the first one. Say, for example, you are making a typo:
For object comparisons, typically we use this:
Happy coding! :-)
P.S. : This style applies to all programming languages. Even in languages like Pascal where '=' is meant for comparison and ':=' for assignments, there is no harm in using this style of coding.
--Varun
if (myAge = 23) {
// Some code
}
The semantic got changed by this. Being a valid programming statement, compilers wont catch these. [Of course, modern day compilers can be configured to catch them as warnings / errors] . But, if the same typo is made in the second form, the compilers will catch this case as we are trying to modify a constant value.
For object comparisons, typically we use this:
if (strName.equals("varun")) {
// Some code
}
Here, again, we might run into problems if the object is null. NullPointerException need to be caught and a whole lot of stuff need to be done. Instead use this style:
if ("varun".equals(strName)) {This style is safe even if the object is null.
// Some code
}
Happy coding! :-)
P.S. : This style applies to all programming languages. Even in languages like Pascal where '=' is meant for comparison and ':=' for assignments, there is no harm in using this style of coding.
--Varun
No comments:
Post a Comment