Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean parameters - should I name them?

Tags:

coding-style

so i just came across some code that reads like so:

checkCalculationPeriodFrequency("7D", "7D", SHOULD_MATCH);

and

checkCalculationPeriodFrequency("7D", "8D", SHOULD_NOT_MATCH);

Let's not worry about what the code does for now (or indeed, ever), but instead, let's worry about that last parameter - the SHOULD_MATCH and SHOULD_NOT_MATCH

Its something i've thought of before but thought might be "bad" to do (inasmuch as "bad" holds any real meaning in a postmodernist world).

above, those values are declared (as you might have assumed):

private boolean SHOULD_MATCH = true;
private boolean SHOULD_NOT_MATCH = false;

I can't recall reading about "naming" the boolean parameter passed to a method call to ease readability, but it certainly makes sense (for readability, but then, it also hides what the value is, if only a teeny bit). Is this a style thing that others have found is instagram or like, soooo facebook?

like image 495
bharal Avatar asked Dec 26 '22 18:12

bharal


1 Answers

Naming the argument would help with readability, especially when the alternative is usually something like

checkCalculationFrequency("7D",
                          "8D",
                          true /* should match */);

which is ugly. Having context-specific constants could be a solution to this.

I would actually go a step further and redefine the function prototype to accept an enum instead:

enum MatchType {
    ShouldMatch,
    ShouldNotMatch
};

void checkCalculationFrequency(string a, string b, MatchType match);

I would prefer this over a boolean, because it gives you flexibility to extend the function to accept other MatchTypes later.

like image 148
Anthony Avatar answered Jan 31 '23 17:01

Anthony