As far as I know, declaring an interface is like so:
public interface Roots_Squares {
public double square_root( double value );
}
Now… how do you enforce value to have non-negative values? Such a function should avoid negative values right? If someone creates a class that implements this, and that implementation does not handle negative values, and then I use their class with a negative value… well, things break.
It then becomes my responsibility to check for negatives when I’m pretty sure the implementor should do the checking.
4
As explained a bit more thoroughly in this answer, that’s (part of the) price you pay for an interface. If you want to be able to use new implementations of your abstraction at any time, you have no way of forcing those implementations to be correct.
10
The comments on Doval’s answer are right: create and use a PositiveDouble. Also, consider using a design by contract tool. A design by contract tool like cofoja might solve your problem. I have not used 1 but I know that there are several design by contract tools in Java.
1
Your interface should document how it handles bogus input, and can declare Exceptions it will throw. In this case, a simple
@throws IllegalArgumentException
would do the trick.
Doval’s answer is outdated now. You can use an enforce parameter properties(check arguments) in the interface:
public interface Math {
/**
* @throws IllegalArgumentException if value <= 0
*/
default public void sqrt(Double value) {
if(value <= 0) throw new IllegalArgumentException("value must be greater than 0");
squareRoot(value);
}
public void squareRoot(Double value);
}
1