Re:What is wrong with NULL
by carsongross on Monday August 31, 2015 @05:30PM
(#10149224)
You shouldn't have to specify the error states in each method, this is why what I'm advocating is different than a simple enum:
- You don't need to define a constructor to take the error string
- You don't need to implement method dispatch (all methods of an error state instance automatically throw, like null does)
Enums are close, but not quite right.
Hm, I think what you might want is an enum / sum type, but with the ability to state that a particular variable is statically a particular variant of that enum. So, for instance, I can write fn serve(conn: &Connection::ValidConnection), and it's a type error to pass a generic unchecked Connection to it. Then serve() can go and call other functions that take a ValidConnection without doing any further error handling.
You might, for convenience, have a single method that turns a Connection to a ValidConnection, or else throws, and you can encode your error messages in one place in this method.
I think this proposal permits such a thing, although I haven't read it closely yet: http://smallcultfollowing.com/babysteps/blog/2015/08/20/virt...
Then all your call sites can do one of two things. Either they can check for specific errors, like
or you can write a simple function that throws an exception, if you really want an exception-handling style: and then call conn.get_fd(). For a simple command-line app, panicking and aborting is pretty much what you'd want to do anyway. For a test suite, panics are caught per test case (and you can even test that a function does panic with a given message), so it's very testable.