[英]Restrict the return value of an interface to a range in implementing classes
我正在編寫一個小型庫,其中有一些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;
}
}
並返回此值而不是double
但這感覺還不夠好,因為此后您要使用0到10之間的double
值,而不是DoubleBetweenZeroAndTen
。
如果不可能明確禁止這樣做,那么確保用戶不會違反的最佳方法是什么? (現在,我在javadoc中有一個通知。)
您不能明確禁止實現您的接口的人員從whatsYourFavoriteNumberBetweenZeroAndTen()
方法返回任何double
whatsYourFavoriteNumberBetweenZeroAndTen()
值。
您只能在接口的Javadoc中定義返回值的預期范圍,作為接口定義的合同的一部分。 假設您的庫具有使用該接口的實現的類,如果該方法返回的值違反了您規定的約定,則這些類可能會引發異常。
這是JDK中的標准做法,例如, Comparator
的compare()
方法的約定定義了所有實現的預期行為,並且不遵循約定可能會導致在使用JDK實現的JDK類中出現異常或意外結果。接口(例如Collections.sort(List<T> list, Comparator<? super T> c)
, IllegalArgumentException (optional) if the comparator is found to violate the Comparator contract
,則其Javadoc聲明其接口可能拋出IllegalArgumentException (optional) if the comparator is found to violate the Comparator contract
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.