If you're going to use return values to indicate errors (and certainly I feel that there are reasons to use them, exceptions vs error codes is not an either/or proposition IMO), you should use sum types and return either an error or the correct value and have a mechanism to make sure you handle both cases.
ML and Haskell get this right, it's a shame Go overlooked them in this regard.
Why would you even be interested in the float when there's an error?
Consider the following code:
foo, err := strconv.ParseFloat(...)
If you don't handle the error (e.g. by forgetting), the compiler will show an error because you declared err, but didn't use it.If you write
foo, _ := strconv.ParseFloat(...)
instead, you deliberately choose to ignore the error.> In a decent language, you get either an error or a float, you have no way to accidently use the float if an error occurred.
Making these specifics a criteria for decency is nothing but arrogance.
But if I make a mistake like I mentioned previously, I could very well use err, thus not getting a compiler warning, and still also use foo, which is a whoknowswhat. It should be an Either, not two seperate return values.
>Making these specifics a criteria for decency is nothing but arrogance.
Having opinions is not arrogance. You should consider that when someone shares their opinion, they are not declaring that everyone everywhere must acknowledge it as a universal truth.
Right x = leftOrRight y
And get a runtime crash when a Left shows up, Or
Just x = justOrNone y
And crash on None.Of course it exists: don't unpack the result and ignore it or pass it along, or use it through its monadic or applicative interface (to proxy-with-transform to the caller).
a, _ := some_computation_that_may_fail()
b := f(a)
In Go, if there was an error in `some_computation_that_may_fail`, the call to `f` will be made with a undetermined value for `a` and we end up with an undetermined value for `b`. This is why I say that there is a path where we can use `a` even when we shouldn't.Compare with OCaml:
let Some a = some_computation_that_may_fail () in
let b = f a
First of all, the compiler will warn you that the pattern matching on line 1 is non-exhaustive and will give you an example of a failing case (here, it will simply be `None`). If the programmer ignores that warning and runs the program anyway and the computation executes with an error, the program will fail at the first line, and thus the second function `f` will never be called and `b` will not contain an undetermined value.I hope this clears up what I meant, I apologize that I wasn't clearer in the first place. Cheers!
But in order to live in peace you have to either:
* Force every programmer to always check all the error values.
or
* Allow errors to pass silently.
So either you accept Go as a heavy-duty, heavy boilerplate error handling laden language. Or you accept it as a flaky, risky language.
Exceptions are the better compromise in my opinion. You get much cleaner code.
If this is the more common pattern for your programming life:
try:
f = float(someText)
use_it_here(f)
use_it_there(f)
catch Exception:
# I wanted to do things, but something went wrong.
# Here's what to do now, this is easy
Then you're better off using exceptions. If you need to check every single call (e.g. NASA or Kernel programming) then you might prefer this: if f, err := strconv.ParseFloat(text); err != nil {
// do something
}
if f, err := use_it_here(text); err != nil {
// do something
}
if f, err := use_it_there(text); err != nil {
// do something
}Given this, I don't see how Go is any worse with respect to sloppy programmers. They'll Always Find A Way.
Also, why couldn't your second example be nested? It seems like either of those two examples could be structured identically to the other.
Errors should never pass silently
Unless explicitly silenced
The problem with go is that you have 3 error modes:1. Explicitly handle everything
2. Implicitly silence sometimes
3. Panic/recover explodes sometimes (who knows where/when?)
Mode #2 is dangerous.
Java/Python give you 2 only modes:
1. Implicitly explode on error.
2. Explicitly silence sometimes.
Where both modes aren't inherently dangerous, i.e. they won't directly cause undefined states to execute.
--------------------
Concerning the nesting in my examples - I'm used to the style of C programming where failing is mostly handled by a return as to keep the program as readable (and thus flat) as possible. So pardon my french but I assumed "// do something" would somehow prevent further usage of 'f'.
Note that the Go example, although tedious, isn't bad in cases where you really do need to check every single possible error.
You could certainly argue for handling each message in a separate process a la erlang, but this approach worked well for us.
I think checked exceptions were a mistake (IIRC Gosling agrees), and Java could do with better support for multiple return values (which exceptions get abused for), but I like Java-style runtime exceptions.
I'm pretty sure you wouldn't do that. You'd have a shallow tree of processes, each leaf process would be tasked with doing message processing e.g. provided by its supervisor. The supervisor would "manage the queue" so to speak, and depending on the semantics of the queue it would have 1 to n children; and it would be tasked with marking failed messages when a child process would blow up (and restarting a new child).
Modelling messages as processes would likely be impractical.
with open("x.txt") as f:
#do stuff with f
That's it. Obviously, compared to 'defer', it hides stuff - the actual magic happens in special methods __enter__ and __exit__ of the object passed to 'with'. def withSomeResource
handle = acquireSomeResource
yield handle
ensure
freeSomeResource(handle) if handle
end
withSomeResource do |h|
h.whatever
end
File.open and other parts of the standard library does that by default. I imagine the Python implementation of "with" is pretty similar, given that it can be implemented pretty much like this in Ruby, and "(begin) .. ensure .." is pretty much equivalent to "try ... finally ..": def with r
r.__enter__
yield(r)
ensure
r.__exit__
endPython's 'with' inverts the control - the control is with the language runtime and the resource is passive here. In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime. The resource itself (or the contextmanager representing it) only implements __enter__ and __exit__ and is passive with regards to this mechanism.
Where the method is doesn't matter, e.g. the (incomplete) example I gave of implementing "with" in Ruby that shows a method that can be defined in the global "main" scope or wherever you want.
Some classes implement class-methods to instantiate an object and pass it to a black and free the resource as a convenience, such as File.open, but it could go wherever else.
The resource itself most certainly does not need to know a thing about it as long as its API lets you do the cleanup you want/need.
> The control is with the resource.
The control is with whatever calls yield. Whether that be a method on the global "main" object (closest thing Ruby has to a global, freestanding function) or on the class of the resource itself, or an explicit "begin ... ensure ... end" block if you only need it once.
> In fact 'with' is a special syntax extension, with calls to hard coded method names (__enter__ and __exit__) done by the Python runtime.
Which is why I gave my example of how I thought "with" would look like in Ruby (as it turns out I missed some exception handling in order for it to be equivalent to the Python version in functionality).
What you can't do, though, is express ruby's blocks using python's with statement; ruby is strictly more powerful here. One simple example of this is ruby's fork statement, which runs the code in the block in a process of its own:
fork { puts "child" }
puts "parent"
That will print "child" and "parent" once each, and it works because the fork method has control over the block's execution, so it can choose to only evaluate the block in the child's context. In python, the approximate code would be: with fork():
print 'child'
print 'parent'
However, python doesn't allow the resource to control block execution, so this code can't work (within standard python; there's a bytecode hack that can make it work, but that's outside the spec). Anyhow, I guess we've diverged pretty hard from the article, but I can never pass up the opportunity to vent against python's with statement.Note that there's a difference in the handling of exceptions: if an exception is triggered from the `with` block, it is intercepted, provided to __exit__ and can be silenced if needed or desired (by returning a truthy value). So a closer approximation would be:
def with r
r.__enter__
begin
yield(r)
rescue Exception => e
raise unless r.__exit__(e)
else
r.__exit__(nil)
end
endThen again, `f.Close()` could hide any "magic" you want as well.
try (FileInputStream f = new FileInputStream(path)) {
// do stuff
}No, you have it exactly backwards. It's with return values that you have to check after every call to be safe. With exceptions you can truly say: if I don't know what to do if this fails then I don't do anything. You can let the exception bubble up higher, all the way up to crashing the program if you like (which gives a nice stack trace that can then be debugged).
With return values, if you don't check then you could be building up more and more trash and you won't even know it until you either hit a point of code that finally does look at what's returned, or if an exception occurs (e.g. segfault).
try:
f = float(someText)
catch ValueError:
# I just parsed you, this is crazy,
# here's an exception, throw it maybe?
Formatted That For You
There are two general use cases for exceptions:
1. Unexpected (typically fatal) problems;
2. As an alternative to multiple return values.
(1) is things like out of memory errors. (2) is things like you're trying to parse a user input into a number and it fails. I despise (2) for exceptions. It means writing code like:
where this gets particularly irritating is when you start writing code like this: I nearly always end up writing wrapper functions around that crap.Java is worse for this because some libraries (including standard ones) abuse checked exceptions for this. I actually prefer:
or even: for this kind of scenario.For the truly bad--typically fatal--error conditions and cleanup, IMHO defer/panic actually works quite well. I certainly prefer this:
to: as Go puts the two relevant things together.Don't get me wrong: I like Python too but I do think Go has a lot going for it and has a bright future.