Avoid Unnecessary Comparisons

 class​ Laboratory {
 
  Microscope microscope;
 
  Result analyze(Sample sample) {
»if​ (microscope.isInorganic(sample) == ​true​) {
 return​ Result.INORGANIC;
  } ​else​ {
 return​ analyzeOrganic(sample);
  }
  }
 
 private​ Result analyzeOrganic(Sample sample) {
»if​ (microscope.isHumanoid(sample) == ​false​) {
 return​ Result.ALIEN;
  } ​else​ {
 return​ Result.HUMANOID;
  }
  }
 }

The first logical conditions you learned to write probably consisted of integers and comparison operators, and a beginner might use that same way of implementing conditions with boolean values. But those comparisons are completely unnecessary—they’re like noise in your code.

Here you can see code for a Laboratory component, which analyzes a Sample through conditions in two nested if-else blocks.

The code explicitly compares boolean return values to boolean primitive types (true and false). This is an anti-pattern that you can often find in code written by beginners.

If you build logical conditions with data types other than boolean, for example with integers, you need to compare them to actual values (e.g., myNumber == 25, input > 0). But you don’t need to do that for boolean variables or return types.

Instead, you already have boolean expressions to work with. There’s no need to compare them to boolean primitives. The comparisons clutter up the code and make it just a little harder to read.

Most of the time, you’ll find that it’s straightforward to get rid of such unnecessary comparisons. Not only will you have less code, but it will also be easier to read.

Now check out how straightforward this code is without those comparisons.

 class​ Laboratory {
 
  Microscope microscope;
 
  Result analyze(Sample sample) {
»if​ (microscope.isInorganic(sample)) {
 return​ Result.INORGANIC;
  } ​else​ {
 return​ analyzeOrganic(sample);
  }
  }
 
 private​ Result analyzeOrganic(Sample sample) {
»if​ (!microscope.isHumanoid(sample)) {
 return​ Result.ALIEN;
  } ​else​ {
 return​ Result.HUMANOID;
  }
  }
 }

Here, we removed the comparisons to boolean primitives. In the case of laboratory.isHumanoid(sample), we had to negate the expression to retain the semantics. But otherwise, the code is unchanged. You can now read the condition expressions a little more easily.

Any compiler would perform such a removal out-of-the-box. There’s probably no difference between the two snippets in terms of the actual execution. The benefit here lies entirely in the readability of the code. It’s a small fix in some simple code, but imagine you’re working with a large code base—every little improvement in readability helps!

Thinking about Avoid Negations, you could improve the conditions even further. So read on!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.12.156