HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Boolean expression complexity and bitwise operators

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
expressionbooleanbitwiseandoperatorscomplexity

Problem

Given this kind of code:

public static final int DEFAULT_MASK = Mask.BASE
    | Mask.SECTOR
    | Mask.GROUP
    | Mask.INDUSTRY
    | Mask.NAME
    | Mask.COUNTRY;


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 {
    int tmp = Mask.BASE;
    tmp |= Mask.SECTOR;
    tmp |= Mask.GROUP;
    tmp |= Mask.INDUSTRY;
    tmp |= Mask.NAME;
    tmp |= Mask.COUNTRY;
    DEFAULT_MASK = tmp;
}


... 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.

Solution

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
    | Mask.SECTOR
    | Mask.GROUP
    | Mask.INDUSTRY
    | Mask.NAME
    | Mask.COUNTRY;

Code Snippets

result = a & b | c | d & x & y
mask = a | b | c | d
public static final int DEFAULT_MASK = Mask.BASE  // NOSONAR
    | Mask.SECTOR
    | Mask.GROUP
    | Mask.INDUSTRY
    | Mask.NAME
    | Mask.COUNTRY;

Context

StackExchange Code Review Q#39956, answer score: 9

Revisions (0)

No revisions yet.