Results tagged “Constants”

Tip #4 of the Java Tips series is just a quick tip to enhance the codes robustness.


Advice

When comparing constants, always compare the constant to the unknown value.

Code-Example

Before

if(str != null && str.equals("XYZ")) { ... }
if(value != null && value.equals(SomeEnum.ENUM_1)) { ... }

After

if("XYZ".equals(str)) { ... }
if(SomeEnum.ENUM_1.equals(value)) { ... }

Benefit

Safety gain. Minor readability gain. The constant value can be compared to a null value without resulting in a NullPointerException. The check for null can be skipped because when the constant is compared to null the condition simply evaluates to a boolean false.

Remarks

None.

|

1

Archives