avatar

Bhuwan Upadhyay

Talks all about software engineering

Published on

Do not make unnecessary comparisons in java

Authors

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