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);
      }
   }
}

Answer

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

doStuffBasedOnABooleanFlag(false);
doStuffBasedOnABooleanFlag(true);

Less code, more obvious, more efficient.

Leave a Reply

Your email address will not be published. Required fields are marked *