One small Java habit that saved me from bugs 👇 Instead of writing: if (str.equals("test")) { // logic } I now write: if ("test".equals(str)) { // logic } 👉 Why this works better? If "str" is null: - str.equals("test") → 💥 NullPointerException - "test".equals(str) → returns false ✅ (no error) 👉 Because: "test" is a real object, so calling equals() is always safe. 💡 Simple change… but very useful in real projects. Do you follow this pattern? 👇 #Java #CoreJava #Programming #BackendDeveloper #Coding #TechLearning
I don't follow this pattern because the question is whether str can be null or not. If str cannot be null, the first way will lead to an NPE that shows the bug. The second way will swallow the but, and you will never find out.
Anyone heard of commons.StringUtils?? 😅
Oldie but goldie this is Prashant Panwar.Thanks for the good explanation.I'd like to add that those should be rarely used - they smell. Its defensive programming and should not/ rarely be necessary in a well known software architecture. Even if they exist their occurence ought to be typically isolated within a specific single layer of the application.Yes - I know: The reality in established code bases looks different ;-)
I like approach #2... but:Have not had NPE in production in over 10 years. Why? - Static code analysis (Sonar and IntelliJ suggestions) - Checkstyle adherence - Extensive testing and code coverage - Using patterns that do not yield NPE (such as above) - Using Modern Java techiques
Works well,But Objects.equals(str, "test") is cleaner and more readable in modern Java.
why not equalsIgnoreCase() for string comparison? isn’t equals() is for comparing objects?
Also, with Java 7+, Objects.equals(str, "test") is another clean and null-safe option.
Prashant Panwar In earlier days of my career, I also used to define it the 1st way later on I discovered the 2nd approach is much better and reliable.
Good way to do that
I don't follow this and I never liked it. Code should sound like natural English as much as possible, and no one says 'if empty is the box'. If str should never be null, this will swallow the bug silently. So I use if( str.equals("test")) // str should never be null or, if str may be null if ( str != null && str.equals("test") ) // shows intent, readable