Is there a way to allow only an Int parameter of a function within a Range

Viewed 239

I am trying to figure out a way to limit an int parameter when calling a giving function as long as the int value is within a certain range. For example:

class A{
    void doSomething(int nValueWithin10And214){}
}

class B{
    A objA = new A();
    objA.doSomething(int someValue)   //Here already know the limitation of the parameter
}

I already know to check inside the function if the parameter is within a range, but I'm looking a way when the caller already knows the limitation.

Should I create a custom throwable in these cases and the caller throws an exception when it's not within the range?

Should I create a custom object extending an Integer so the function called and the caller already comply with the requirements?

What would be the recommended way?

Any thoughts?

2 Answers

No, there is no way, in Java SE, to limit by default, your method parameter's possible values' range; however, there are some Bean Validation framework(s), which might help you to achieve your desired functionality. Hibernate's Validator (The Bean Validation reference implementation) is one very popular framework you can reference.

But no, no such a specification has ever been implemented to Java core language.

I think the best way to do this is by throwing an exception if the parameter is outside the range, as you mentioned yourself. Like this:

void doSomething(int nValueWithin10And214){
    if (nValueWithin10and214 < 10 || nValueWithin10and214 > 214 {
        throw new ValueNotInRangeException();
    }
}
Related