Is it a good practice to make all interface (trait) methods for which there may exist a future implementation with invalid arguments returning an option?
Let me give an example. If I would implement a library for probability distributions with a trait
trait Similarity {
def getDensity(): Double
}
Since most distributions are not defined over the whole real space, there are always some illegal parameters e.g. a non-positive variance for a Gaussian distribution. If I understood it correctly, I should return an Option[Double] rather than a Double and throwing an IllegalArgumentException.
I think the same is true for most functions/calculations. What is “best practice” in this case? I am afraid this would make a library overly clumsy.
Thanks
I wouldn’t throw an IllegalArgumentException as it is not the arguments that are the problem, but the state of the object. If it were to be an exception, IllegalStateException would match.
However, the real answer depends on what you expect the caller to do in the case of a problem.
If they would themselves throw an exception, that’s what you should do, saving them the bother.
If they would do something different based on the answer being impossible, an Option[Double] is a good indicator.
A possibility worth knowing of, but less likely to be useful, is Double.NaN, effectively a Null Object but for Doubles.