educative.io

Simplify verbose code

This code:

		if (nums[currentIndex] >= 0) {
			nextDirection = true;
		}
		else
		    nextDirection = false;

can be simplified as nextDirection = nums[currentIndex] >= 0;


Course: https://www.educative.io/courses/grokking-coding-interview-patterns-java
Lesson: Solution: Circular Array Loop - Grokking Coding Interview Patterns in Java

Hi @Drago_Kamenov

You’re absolutely right; this way of simplifying the if-else block works. On the contrary, you could also use a conditional ternary operator like the following:

nextDirection = nums[currentIndex] >= 0 ? true : false

However a beginner might not be familiar with the above two notations which is why we decided to currently keep it simple with an if-else block.

However, thank you for your feedback. We will take your suggestion into consideration.

correct - it is a beginner’s mistake. Since nums[currentIndex] >= 0 is a boolean expression, there is no need for if-else or ternary operator to assign its value to a boolean variable. Anyone who is taking this class should be familiar with such basic programming concepts