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

Optimizing boolean checking method

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

Problem

I have written a method that checks if n number of true booleans are present in a boolean[] array. Then I improved it to var args format which is as follows:

public static boolean checkNTrue(int n, boolean... args) {
    assert args.length > 0;
    int count = 0;
    for( boolean b : args ) {
        if(b)   count++;
        if( count > n )
            return false;
    }
    return ( count == n );
}


I implement it to check if only one of all those booleans is true by using:

boolean result = checkNTrue(1, false, true, false, false);


The above returns true confirming the required case. But what if there are only two boolean arguments? A simple XOR could return the right result.

And in the case of 3 booleans, return (a ^ b ^ c) ^ (a && b && c); works fine too. So, my question is:

Do I need to write separate methods to check in cases with 2 and 3 variables?

Or will this one method do fine? I invite every kind of criticism through downvotes and comments, but please enlighten me! :-)

Solution

Premature optimization is a bad idea. Before you try to optimize anything, run a profiler to measure where your bottlenecks are. Unless you are running this function in a tight loop, it's unlikely that this function will be a bottleneck.

The special cases that you would introduce don't come for free:

  • The more line of code you write, the more bugs you are likely to have, statistically.



  • Your unit tests also have to address the special cases.



  • There is a bit of overhead in checking whether your special cases apply.



Taking all that into consideration, it's almost certainly not worthwhile to add special cases.

The assertion assert args.length > 0 might be inappropriate. Considering this code in a vacuum, there is nothing to guarantee that that assertion is logically true. Rather, it's a runtime validation check. Validation failures should throw an IllegalArgumentException. They shouldn't be assertion failures. (Assertions can be disabled, defeating your check.)

If this were a non-public method, and you are sure that you've written your code such that all call sites have at least two arguments, then an assertion might be appropriate.

Here's a philosophical question: should checkNTrue(0) be true or false? I think it should be true.

Context

StackExchange Code Review Q#44357, answer score: 11

Revisions (0)

No revisions yet.