Every so often I come across these simple things that after thinking about them I kick myself for not thinking about and knowing sooner. Earlier today was one of those moments!
It might seem natural, assumed, even obvious that for many method calls it doesn't actually matter what way around things go. So take
In this case, no - but what about if we introduce variables?
Again, no difference. Now let's be a bit sneaky however and swap str to null (you may see where this is going!)
Ahah! This time we (somewhat obviously) get a NPE on the third line. But the second line executes without any problems at all (also rather obviously - we're not dereferencing null here!)
Conclusion? When comparing strings, it makes much more sense to adopt a design pattern of putting the literal first rather than a variable name. If this is the case and if the variable happens to be null, then equals will just return false rather than causing an NPE. 99% of time this is the desired behaviour, unless you know your strings should never be null and want to be screamed at if they are. Even so, it'd probably make more sense in this case to put a separate check in rather than relying on the order of the values to give you an NPE - that could easily disappear when someone else comes along and reverses the order without realising it was intentionally the other way around :-)
It might seem natural, assumed, even obvious that for many method calls it doesn't actually matter what way around things go. So take
"asd".equals("dsa");
- does it ever make a difference?In this case, no - but what about if we introduce variables?
String str = "asd";
System.out.println(str.equals("dsa"));
System.out.println("dsa".equals(str));
Again, no difference. Now let's be a bit sneaky however and swap str to null (you may see where this is going!)
String str = null;
System.out.println("dsa".equals(str));
System.out.println(str.equals("dsa"));
Ahah! This time we (somewhat obviously) get a NPE on the third line. But the second line executes without any problems at all (also rather obviously - we're not dereferencing null here!)
Conclusion? When comparing strings, it makes much more sense to adopt a design pattern of putting the literal first rather than a variable name. If this is the case and if the variable happens to be null, then equals will just return false rather than causing an NPE. 99% of time this is the desired behaviour, unless you know your strings should never be null and want to be screamed at if they are. Even so, it'd probably make more sense in this case to put a separate check in rather than relying on the order of the values to give you an NPE - that could easily disappear when someone else comes along and reverses the order without realising it was intentionally the other way around :-)
Comments
Post a Comment