4

我正在编写一个小型库,其中有一些interface提供返回值应在指定范围内的方法。如何明确禁止实现此方法的库用户返回不在此范围内的值?

像这样的东西:

//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
    }

}

我想我可以写一些类似的东西

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;
    }
}

并返回 this 而不是 thedouble但这感觉不够好,因为它是一个double介于 0 和 10 之间的你想要使用的,而不是DoubleBetweenZeroAndTen.

如果无法明确禁止,那么确保用户不会违反它的最佳方法是什么?(现在,我在 javadoc 中有一个通知。)

4

1 回答 1

1

You can't explicitly forbid people who implement your interface from returning any double value from the whatsYourFavoriteNumberBetweenZeroAndTen() method.

You can only define the expected range of returned values in the Javadoc of the interface, as part of the contract defined by the interface. Assuming your library has classes that use implementations of that interface, these classes may throw an exception if that method returns a value that violates your stated contract.

This is a standard practice in the JDK - for example, the contract of Comparator's compare() method defines the expected behavior of all implementations, and not following the contract could lead to exceptions or unexpected results in JDK classes that use implementations of the interface (such as Collections.sort(List<T> list, Comparator<? super T> c), whose Javadoc states it may throw IllegalArgumentException (optional) if the comparator is found to violate the Comparator contract).

于 2017-06-21T08:41:36.470 回答