Tony
Tony

Reputation: 1155

I don't understand the difference

I was reviewing some Java code with this line

if ( list.size() == 1 || list.size() <= 4) {...}

I commented that I do not see how that is any different from just doing

if (list.size() <= 4) {...}

he said it matters and needs to be the first. I don't understand. Perhaps if it were something like

if (list.size() == 1 || list.size() <= someVeryCostlyFunction() ) {...}

and the size was expected to be 1 most of the time you might use both, if someVeryCostlyFunction() always returns some positive number >= 1. Otherwise I can't see the difference. We are supposed to check for efficiency.

Upvotes: 0

Views: 77

Answers (1)

MaxZoom
MaxZoom

Reputation: 7753

The code smells with those two conditions:

if (list.size() == 1 || list.size() <= 4)

Perhaps the author have that in mind:

if there is some number of elements in the list that is 4 or less.

More over the current code allows to satisfy the condition even if the list has zero elements - which is most likely wrong.

Another problem with this condition is use of magic number 4?
What is so important about it and why it is not 5? It should be self documented and distinguished from other 4's that could appear in the code:

int MAX_HANDLED = 4;
if ( list.size() > 0 && list.size() <= MAX_HANDLED )
:
:
int ALL_TIRES = 4;
if (car.getTires() < ALL_TIRES) {
  car.stop();
}

As for the performance, I do not see any significant reason why existing condition should be any faster then yours proposed one (even the second would be faster when list.size > 1). See this question of similar concern.

Upvotes: 1

Related Questions