2

I was just discussing a method with colleague, the usage looks a little like this:

String myString = getString(fields[10], true);

Now here's my question, what does true do?

The obvious answer is to look at the method definition and see what it does with that boolean, but why do I need to do that? Is there a better coding style that will explain the purpose of the boolean right there in the method call?

I thought initially to change the method to accept a specific string, but that's far too loose.

The best idea I can come up with is to create a local boolean, like this:

boolean thisShouldBeUpperCased = true;

String myString = getString(fields[10], thisShouldBeUpperCased);

Has anyone come across this before, is there a better way?

Gary Lyons
  • 23
  • 2
  • There is a good discussion about this on the Programmers site. http://programmers.stackexchange.com/questions/147977/is-it-wrong-to-use-a-boolean-parameter-to-determine-behavior/148058#148058 – Rob Kielty Nov 08 '12 at 14:37

1 Answers1

0

Typically in a C-like language you might use consts or enums to improve readability, e.g.

const bool kConvertToUpperCase = true;
const bool kDoNotConvertToUpperCase = false;

or

enum {
    kDoNotConvertToUpperCase,
    kConvertToUpperCase
};

The above methods also allow for extensibility, e.g. if a design initially calls for two possible options for a particular parameter, which might then be implemented as a boolean, but later this becomes three (or more) options, requiring an int or an enum - you don't then need to switch form explicit true/false literals everywhere to their equivalent values.

E.g.

const int kConvertToLowerCase = 2;
const int kConvertToUpperCase = 1;
const int kDoNotConvertToUpperCase = 0;

or

enum {
    kDoNotConvertToUpperCase,
    kConvertToUpperCase,
    kConvertToLowerCase
};
Paul R
  • 208,748
  • 37
  • 389
  • 560