Search code examples
stylesbooleanclarity

Coding Style for passing boolean parameters


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?


Solution

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