burnedWood
burnedWood

Reputation: 93

Refering to arguments of Java methods

Suppose that I want to check all parameters of a method for negativity. I could do something like this:

public class test{
    public test(double a, double b, int c, int d, long e ,  long f){

        // check parameter correctness
        checkNegParam(a,"1");
        checkNegParam(b,"2");
        checkNegParam(c,"3");
        checkNegParam(d,"4");
        checkNegParam(e,"5");
        checkNegParam(f,"6");   
    }

    private void checkNegParam(double number, String order) {
        if (number < 0) {
            throw new IllegalArgumentException("Argument"+ order +" is negative");
        }
    }
}

However, I really don't like this approach. Is there a way to refer to the method parameters by their order numbering? Also, is there a way to refer to a primitive and check for negativity without reference to its exact type?

Upvotes: 1

Views: 59

Answers (3)

wassgren
wassgren

Reputation: 19211

The following piece of code might help you with a more general way of finding negative parameters:

private void assertNotNegative(Number... numbers) {
    for (int i = 0; i < numbers.length; i++) {
        if (Math.signum(numbers[i].doubleValue()) < 0) {
            throw new IllegalStateException("Negative argument " + numbers[i] + ", index: " + i);
        }
    }
}

To invoke it simply call:

public test(double a, double b, int c, int d, long e ,  long f) {
    assertNotNegative(a, b, c, d, e, f);
}

Upvotes: 0

Mshnik
Mshnik

Reputation: 7032

If you can get all of your arguments in a array or any collection, then you can loop over them and check it that way:

public class test{
    public void test(double[] args) throws IllegalArgumentException{
        for(int i = 0; i < args.length; i++){
            if(args[i] < 0) throw new IllegalArgumentException("Argument " + (i + 1) + " is negative");
        }
    }
}

If you want to retain your calls to this method without constructing arrays/collections yourself, you can get java to do it for you with variable args.

public class test{
    public void test(Double... args) throws IllegalArgumentException{
        for(int i = 0; i < args.length; i++){
            if(args[i] < 0) throw new IllegalArgumentException("Argument " + (i + 1) + " is negative");
        }
    }
}

Upvotes: 0

acanby
acanby

Reputation: 2993

I would recommend that you stick to using named parameters.

Consider the implications if you add a new (possibly positive) parameter at a position other than the end, and forget to update your check to reflect that this can be a positive value. You will waste a lot of time debugging this.

If other people have to use/write this code, then using numbers would obscure the purpose of the code and they will have a hard time understanding what you are doing.

Upvotes: 2

Related Questions