Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: looping on the two boolean values (false, true)

This is a stylistic question. I want to loop twice with a variable on which is set to false, then to true. Which of these is clearer:

A)

for (final boolean on : new boolean[] { false, true} )
{
   doStuffBasedOnABooleanFlag(on);
}

B)

for (int i = 0; i < 2; ++i)
{
   final boolean on = (i == 1);
   doStuffBasedOnABooleanFlag(on);
}

C) something else


edit: Murphy's law of unintended interpretations comes into play... the use case I have originally looked something like this instead of doStuffBasedOnABooleanFlag:

for (final boolean on : new boolean[] { false, true} )
{
   JButton button = on ? onButton : offButton;
   button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent event) {
      doStuffLaterBasedOnABooleanFlag(on);
      }
   }
}

But I think I like Brendan's answer, I'll just refactor the loop contents into a separate method:

doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);

   ...

private void doStuffBasedOnABooleanFlag(final boolean on)
{
   JButton button = on ? onButton : offButton;
   button.addActionListener(new ActionListener() {
      @Override public void actionPerformed(ActionEvent event) {
      doStuffLaterBasedOnABooleanFlag(on);
      }
   }
}
like image 935
Jason S Avatar asked Mar 04 '10 22:03

Jason S


4 Answers

Since it's two lines, I'd just skip the loop and do:

doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);

Less code, more obvious, more efficient.

like image 66
Brendan Long Avatar answered Oct 14 '22 00:10

Brendan Long


Another option would be to avoid the boolean and use an enum:

enum Mode { APPEND, REPLACE } // or whatever your boolean indicated

You could then either iterate:

for(Mode m : Mode.values()) doStuff(m);

Or do the calls directly:

doStuff(Mode.APPEND);
doStuff(Mode.REPLACE);

The advantage of this would be that the API indicates more clearly what's happening.

like image 44
Fabian Steeg Avatar answered Oct 14 '22 00:10

Fabian Steeg


If you really want to use a loop, I would go with (a). While it's novel, it's also clear and efficient. I might move the boolean array to a private static, to avoid recreating the array every time.

But I like Brendan's answer better.

like image 35
Lawrence Dol Avatar answered Oct 14 '22 00:10

Lawrence Dol


It can be done directly within a for loop, without creating a new array.

for (boolean on=false, done=false; !done; done=on, on=true) {
    System.out.println("on="+on+", done="+done);
}

Output:

on=false, done=false
on=true, done=false

This isn't the most clear way, so I wouldn't use this approach unless it were in some kind of inner loop where it would be executed a large number of times.

like image 45
Brent Bradburn Avatar answered Oct 13 '22 23:10

Brent Bradburn