Re:Why Go Gets Exceptions Right
by TylerE on Friday September 14, 2012 @10:06AM
(#4521666)
It appears your code will find the value _twice_. That is less than ideal and not equivalent at all.
[ Parent
| on HN ]
If an assumption can be made that you won't put null values into the map then it can be rewritten where it doesn't need to do the check described above:
value = map.get(key);
if (null == value) {
// Handle no value in the map
}
Any class correctly implementing Map in Java won't throw an exception if there is no value for an input key (http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#...) and some don't allow you to put null values in to begin with (http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable...).I think one of the points of the OP's article is that in Go you don't have to code like you've done here, where a single return value means one of two things (in your example: value in the map, or special reserved value that indicates the key wasn't found in the map). Go is cleaner, even if it's just a small improvement.
The argument used to be how "Go got exceptions right".
Now, it appears that the argument is about how to save a trivial amount of work for the CPU, when it's unclear whether this is a bottleneck, or whether the JIT can optimize away the two calls, or, in the remaining 1% of the cases, using the null idiom makes this a non-issue.
All at the cost of spending 1 of my 7 brain registers to handle "mandatory ceremony" of adding a _ to every map.get call, regardless of whether I actually know that the given map access should never see an unmapped key, which is the vast majority of cases in my day-to-day coding experience.
At the very best, the argument is about "multiple return values are useful in some cases". But tread carefully, lest every caller has to worry about useless return values.