# Boolean expression complexity and bitwise operators

Given this kind of code:

public static final int DEFAULT_MASK = Mask.BASE


Sonar raises a warning:

Boolean expression complexity is 5 (max allowed is 3).

What would be a good way to deal with this?

I suppose the warning might go away if I rewrite like this:

public static final int DEFAULT_MASK;
static {
}


... but this smells (too many mutations, ugly).

UPDATE

In addition to the default mask above, I have a few other masks as well, using different sets of bits, for different purposes. Every bitmask with more than 3 bits would raise a Sonar violation.

• In a vacuum, I'd say that your original code is better than your workaround. However, to do a proper code review, we need more context to understand the root cause of the code smell. How will this mask be used? – 200_success Jan 24 '14 at 11:23
• An automated programm will weigh complexity different than a human reader. Here Sonar's mistake is to confuse the bitwise operators on constants (complexity ~ 1) with short-circuiting logical operators on general expressions (complexity ~ n). I did a write-up on such issues over on programmers. – amon Jan 24 '14 at 11:32

If it’s a complex bitwise operation, like:

result = a & b | c | d & x & y


then it would make perfect sense to raise a violation. On the other hand, this looks like an "innocent" bitmask:

mask = a | b | c | d


An automated tool cannot judge if this is dangerous or not, so it's understandable to raise a flag for this. But in this particular case, it's clearly a false positive.

I put // NOSONAR on the offending line of code to make the warning go away, like this:

public static final int DEFAULT_MASK = Mask.BASE  // NOSONAR


The first expression in the OP is better than its alternative; and as amon said in a comment this warning is IMO a mistake by Sonar.

Therefore, I suggest, see Turning Sonar off for certain code on StackOverflow.

You could do something like the following. It may be better or worse depending on what you want to do:

enum Mask {
BASE(true),
SECTOR(true),
GROUP(true),
...
OTHER(false)
;

private final isDefault;

this.isDefault = isDefault;
}

public boolean isDefault() { return isDefault; }

public boolean intValue() { return 1 << ordinal(); }
}

int result = 0;
}
}
return result;
}


private static final int part1 = Mask.BASE | Mask.SECTOR | Mask.GROUP;