Last active
October 30, 2020 20:22
-
-
Save jovemfelix/ecd11357d9d7b3e779e4b1c950cb7cd3 to your computer and use it in GitHub Desktop.
Best Practices of Equals Testing in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Objects; | |
| class Scratch { | |
| public static void main(String[] args) { | |
| String s = null; | |
| try { | |
| if (!s.equals("XXX")) { | |
| System.out.println("[WRONG-TESTING] NOT EXECUTED!"); | |
| } | |
| } catch (NullPointerException e) { | |
| System.out.println("[WRONG-TESTING] LEAD TO NPE!"); | |
| } | |
| if (!"XXX".equals(s)) { | |
| System.out.println("[BEST_PRACTICE-01] test with constant first!"); | |
| } | |
| if (!Objects.equals("XXX", s)) { // using equals utility | |
| System.out.println("[BEST_PRACTICE-02] doesn't matter the object orders!"); | |
| } | |
| if (!Objects.equals(s, "XXX")) { // using equals utility | |
| System.out.println("[BEST_PRACTICE-02] doesn't matter the object orders!"); | |
| } | |
| if (Objects.equals(s, null)) { // using equals utility | |
| System.out.println("[BEST_PRACTICE-02] NULL == NULL!"); | |
| } | |
| } | |
| } | |
| /* ##### OUTPUT is: | |
| [WRONG-TESTING] LEAD TO NPE! | |
| [BEST_PRACTICE-01] test with constant first! | |
| [BEST_PRACTICE-02] doesn't matter the object orders! | |
| [BEST_PRACTICE-02] doesn't matter the object orders! | |
| [BEST_PRACTICE-02] NULL == NULL! | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment