Limit the return value of an interface to a range in a class implementation

I am writing a small library, where I have one interface, providing a method in which the return value should be in the specified range. How can I explicitly prevent users of my library who implement this method from returning a value not in this range?

Something like that:

//Library
interface FavoriteNumber {

    //returned value must lie between 0 and 10
    double whatsYourFavoriteNumberBetweenZeroAndTen();
}

...

//Classes implemented by user of library
class ILikePi implements FavoriteNumber {

    @Override
    public double whatsYourFavoriteNumberBetweenZeroAndTen() {
        return 3.141; //Should be allowed
    }

}

...

class AnswerToLifeTheUniverseAndEverything implements FavoriteNumber {

    @Override
    public double whatsYourFavoriteNumberBetweenZeroAndTen() {
        return 42; //Should be forbidden
    }

}

I think I could write something like

class DoubleBetweenZeroAndTen {

    private final double value;

    DoubleBetweenZeroAndTen(double value) {
        if (value < 0 || value > 10) {
            throw new IllegalArgumentException("value must be between 0 and 10");
        }
        this.value = value;
    }

    double toDouble() {
        return this.value;
    }
}

and return this instead double, but this is not very good, since it is doublebetween 0 and 10, with which you want to work after that, and not DoubleBetweenZeroAndTen.

If it is not possible to prohibit it explicitly, what is the best way to ensure that the user does not violate it? (Right now, I have a notification in javadoc.)

+4
1

, , double whatsYourFavoriteNumberBetweenZeroAndTen().

Javadoc , , . , , , , , .

JDK - , Comparator compare() , JDK, (, Collections.sort(List<T> list, Comparator<? super T> c), Javadoc , IllegalArgumentException (optional) if the comparator is found to violate the Comparator contract).

+1

Source: https://habr.com/ru/post/1679784/


All Articles