158 words
1 minutes
Do not make unnecessary comparisons in java
2022-05-30

Introduction#

This article shows how to avoid unnecessary comparisons in java. In this article, we will see how to avoid unnecessary comparisons in java. We will see some examples of unnecessary comparisons and how to simplify them.

Comparison with a boolean literal#

Bad Practice: if (student.isPresent() == true) { }
Simplified: if (student.isPresent()) { }
Bad Practice: if (student.isPresent() == false) { }
Simplified: if (!student.isPresent()) { }
Bad Practice: if (student.isPresent() != true) { }
Simplified: if (!student.isPresent()) { }
Bad Practice: if (student.isPresent() != false) { }
Simplified: if (student.isPresent()) { }

&&-ing or ||-ing with false#

Bad Practice: if (student.isPresent() && false) { }
Simplified: Condition will be always false so better to move code in else case
Bad Practice: if (student.isPresent() || false) { }
Simplified: if (student.isPresent()) { }

&&-ing or ||-ing with true#

Bad Practice: if (student.isPresent() && true) { }
Simplified: if (student.isPresent()) { }
Bad Practice: if (student.isPresent() || true) { }
Simplified: Condition will be always false so remove if condition
Do not make unnecessary comparisons in java
https://semusings.dev/posts/2022/2022-05-30-do-not-make-unnecessary-comparisons/
Author
Bhuwan Prasad Upadhyay
Published at
2022-05-30