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

Find min of 3 numbers hardcoded

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

Problem

public static int min(int a, int b, int c)
{
    int result = 0 ;
    if( a  c) result = a ;

    else if( a > b && a  c &&  c  b && b  c) result = b ;
    else if( a > b && a > c && c < b) result = c ;
    return result ;
}


Is it better than nested if statements? Is there a more readable solution than this? To me it looks pretty readable, but I'm not sure whether it can be improved.

Solution

For these things we have java.lang.Math:

public static int min(final int a, final int b, final int c){
    return Math.min(a, Math.min(b, c));
}


Wow, look how short it is!

But it's 3 numbers today, it's 10 tomorrow.

As an alternative, how about an array?

public static int min(int... numbers){
    if (numbers.length == 0){
        throw new IllegalArgumentException("Can't determine smallest element in an empty set");
    }
    int smallest = numbers[0];
    for (int i = 1; i < numbers.length; i++){
        smallest = Math.min(smallest, numbers[i]);
    }
    return smallest;
}


I'd use the java.lang.Math solution, it's very short, and very readable.

Code Snippets

public static int min(final int a, final int b, final int c){
    return Math.min(a, Math.min(b, c));
}
public static int min(int... numbers){
    if (numbers.length == 0){
        throw new IllegalArgumentException("Can't determine smallest element in an empty set");
    }
    int smallest = numbers[0];
    for (int i = 1; i < numbers.length; i++){
        smallest = Math.min(smallest, numbers[i]);
    }
    return smallest;
}

Context

StackExchange Code Review Q#58747, answer score: 73

Revisions (0)

No revisions yet.