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:
interface FavoriteNumber {
double whatsYourFavoriteNumberBetweenZeroAndTen();
}
...
class ILikePi implements FavoriteNumber {
@Override
public double whatsYourFavoriteNumberBetweenZeroAndTen() {
return 3.141;
}
}
...
class AnswerToLifeTheUniverseAndEverything implements FavoriteNumber {
@Override
public double whatsYourFavoriteNumberBetweenZeroAndTen() {
return 42;
}
}
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.)