by lkitching · 5y ago · 0 comments
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.
This still moves the check out of runtime and into a static check. An exception means the error is handled runtime and as I said before is a definitively worse metric.
Let me put it more simply. An exception means that you can compile an error or mistake and it might accidentally make it to production. This happens because exceptions are only thrown on compiled programs during runtime.
An optional means that run time errors of this nature are impossible to happen. A program that throws an exception on division by zero is impossible to even EXIST. This occurs because if the optional is used, the static type checker will prevent such a program from even compiling. That is why it is definitively better.
Your encoding has really changed the meaning of the div function - it now always accepts any two arbitrary ints and always allows the possibility of returning None. So you've weakened both the precondition and the postcondition, which is now easier for the caller but imposes a cost on every location where the return value is used. As the optionality encoded in the value propagates further from the call to div, the context for the source of the missing value is lost. This is 'safer' in the sense of avoiding crashes at runtime but doesn't actually help resolve the actual issue of avoiding a zero divisor when calling div.