HiveBrain v1.2.0
Get Started
← Back to all entries
debugjavaModerate

fix ugly initialisation in while loop over queue

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fixuglywhileloopoverqueueinitialisation

Problem

I have a loop structure, that I really don't like. It's the initialisation I find appalingly ugly. Is there a nicer way to do the following?

Queue queue = getMyQueue();
Integer element = queue.poll();
while (element != null){
  calculate_smart_stuff(element);
  element = queue.poll();
}


A for loop is slightly better, but still has the ugly repetition of the assignment of element in the initialiser and the 'incrementer' I also prefer my for loops to be really easy, and only to be reserved for counting and adding (or substracting in corner cases) 1, as this is how I expect a for loop to behave.

Queue queue = getMyQueue();
for (Integer element = queue.poll(); element != null; element = queue.poll()){
  calculate_smart_stuff(element);
}


Or should I just keep checking the size before assignment like so?

Queue queue = getMyQueue();
while (queue.size() > 0){
  Integer element = queue.poll();
  calculate_smart_stuff(element);
}


What I don't like about this is that I have to check the size every time before getting an element, which itself has a clear indication that the queue was empty.

Are there any better constructs I can use here, or am I just being picky with the last two options?

Solution

It would be better to do

for (Integer element; (element = queue.poll) != null;){

}


Because you don't want element to be in the scope after the loop has ended

Code Snippets

for (Integer element; (element = queue.poll) != null;){

}

Context

StackExchange Code Review Q#2741, answer score: 13

Revisions (0)

No revisions yet.