by lkitching · 5y ago · 0 comments
div(x: Int, y: NonZero[Int]) -> Int
Exceptions at least have the benefit of retaining the location the context for the error occurred which gets lost without extra bookeeping when using optionals. NonZero = NewType(‘NonZero’, int)
if x != 0
x = NonZero(x)
just to call your function, especially since you still have to handle the case where someone does NonZero(x) blindly without checking. Should the constructor throw?The NonZero type should be responsible for checking the wrapped value is non-zero, you will probably want safe and unsafe constructor functions
Int -> Optional[NonZero[Int]]
Int -> NonZero[Int]
where the unsafe version throws.If this is overkill for your application then I'd prefer throwing an exception in div rather than encoding the failure in the return type.