Open file "foobar.dat". If that fails, abort with this error.
Read the first 4 bytes into x.
If that fails, abort with a different error.
Seek to byte x. If that fails, abort with yet another error.
and so on, and so on, over and over again. Python's exceptions are a huge improvement over this pattern of timidly asking permission to do anything. The fact is there are so, so many occasions where you want to abort a computation if one of the many steps along the way goes wrong. Something like Haskell's Maybe monad is a good way of attacking the problem too.But Go has neither. It seems to just offer the bad old clumsy C way and say, "Deal with it." To those who have written real Go programs, I'm honestly wondering: how is this not a pain in the ass?
Honestly, compared to the exception hellscapes I have had to deal with in Java and C++ --- it seems like the path of least surprise. Which incidentally has been my favorite things about Go, the low number of surprises.
A lot of using Go in real work has gone against my expectations. There are a lot of things I initially saw as huge warts (lack of exceptions, generics and import versions), but I liked channels enough (Erlang background) to give it a shot. So far, I have been delighted by using it as a stack (build cycle, deploy method, terse C'ish syntax).
It is something that can be caught with static analysis, however. Someone recently put together an appropriate tool[1] for Go, in fact. It seems to work very well.
In C, you can write code that doesn't overload errors and return values; e.g.,
err = someFunction(&returnValue, param1, param2, param3);
I'm not saying this is common -- and in fact the standard C library does a lot of the overloading you're talking about -- but for your own code and functions, you can separate out errors and return values, as shown above.
http://stackoverflow.com/questions/1853243/c-do-you-really-w...
Some more reasons why exceptions are problematic:
http://mortoray.com/2012/04/02/everything-wrong-with-excepti...
Go's choice I think is very well considered. If reliability is important to you then I believe handling errors explicitly leads to clearer, more correct code.
But writing exception-safe code IS trivial, in basically any language except C++. Garbage collection is all you need in most cases, and try-with-resources/RAII/etc takes care of closing I/O.
Note that Go still needs defer() to reliably take care of the latter, so it's not clear to me what is gained by the omission (or rather, strong deprecation) of exceptions.
static void scanlevel(int num, FILE *fp)
{
filemap_t filemap;
int i;
if (fseek(fp, mapptrs[num-1], SEEK_SET))
error("Can't load level %d from blockman.lvl", num);
if (fread(&filemap, sizeof (filemap_t), 1, fp) < 1)
error("Can't load level %d from blockman.lvl", num);
if (filemap.startx < 0 || filemap.startx >= LEVWIDTH
|| filemap.starty < 0 || filemap.starty >= LEVHEIGHT)
{
error("Level %d is corrupt", num);
}
map.startx = filemap.startx;
map.starty = filemap.starty;
for (i = 0; i < LEVWIDTH*LEVHEIGHT; i++)
{
map.tiles[i] = (tiletype_t)filemap.tiles[i];
if (map.tiles[i] < 0 || map.tiles[i] >= NUMTILES)
error("Level %d is corrupt", num);
}
}
This shows another benefit of exceptions, which is that if uncaught, they stop the program with a traceback of the exact point they occurred. So it's not even necessary to write most of the checks above. `error` here is a routine that aborts the program; you get that behavior by default with exceptions.Whereas in C/Go if I forgot one of those error checks, the error would occur silently, leaving the program in some weird inconsistent state that I never planned for. It would just do something stupid and maybe crash or panic later on, far from the place where the initial error occurred.
I guess I'm just arguing for exceptions, which is old news as languages that have them have been around for quite a while. But Go doesn't offer much of a substitute of which I'm aware. The explanation of how it solves these problems has not been forthcoming.
It'd be interesting to see what you'd do with the code above in C++, and where you'd put the error handling code for diverse errors that might occur reading this particular file.
The Go approach is to handle errors locally, often in the calling method, which makes it clear where they are handled and what the outcome is, and easier to recover gracefully, without unexpected exceptions from code in libraries or other code in the program. Some large users of C++ (like Google) refuse to use C++ exceptions in their own code - so they are not entirely without controversy.
In the code above, if you used exceptions, and relied on the libraries to throw exceptions for errors, you'd have to throw your own exception at:
error("Level %d is corrupt", num);
So you'd have a mix places where exceptions were generated (in unknown lib code, in your code) and an unknown (for the reader) mix of places where they are handled. I'm sure this could be done gracefully, but it does mean errors missed might be handled at a much higher level in the code, far away from where they were generated, which can lead to errors being missed until it is too late to do anything but output a stack trace and exit, which to the user seems equally stupid as crashing or panicking at some later point.
If you exit the program on simple errors like being unable to load a single game file, it's not very pleasant for the user - I'd expect it instead to recover gracefully and show the user an error before continuing, which is easy enough when using Go's pattern of error returns, and harder with exceptions where you have unrolled the stack possibly past the loading code, unless you start handling exceptions in calling code one level up, which looks very much like the error handling of Go. So there are trade-offs to using either method aren't there?
When you're writing reusable library code (and when you think about the scale of Google's codebase, they must have an insane amount of these libraries), it's important to make this distinction. There are some error conditions where you really just want to say "if this ever happens, just die, because there's nothing sane to be done", and Go provides panic() for these situations, similar to the error() function in your code above.
For situations where you do want to return a meaningful error to the client, I think Go's multiple return values provide a very good way to do it, far better than the overloading of NULL or -1 that you find in C and C++.
You can't actually write code like that in Go, by the way. It's not going to let you read data directly into a struct like that, nor should you really be doing so in the first place.
I'd be happy to provide a more detailed analysis, and possibly even Go-equivalent code, but without further context (at least the definitions for `filemap_t` and whatever struct type `map` is, if not a full description of the file format and its meaning), it's impractical.
The spec is well written and tiny compared to most languages, and it's probably the only thoroughly accurate and complete Go reference at the moment.
Step 1. http://tour.golang.org/ Step 2. http://golang.org/ref/spec
Shockingly few developers will read the f*cking spec for anything. It mystifies -- or perhaps terrifies -- me. It's one of the criteria I try to use to judge if I'm dealing with someone who seeks to truly solve problems, or just keep the build light from turning red.
Some specs are actually kind of fun to read. POSIX is surprisingly pleasant, and sometimes amusing in a "Why is THAT warning label there?" kind of way.
You don't have to treat them like a novel, but many are excellent reference material to keep at your fingertips.
Hopefully these are individual developers shifting through a continuum of enlightenment, rather than the conversation itself migrating to a more enlightened population.
This last question is testable, of course, though sadly HN does not offer an official API.
The crowd that remains is mostly composed of people who have never used an ML-style language (Haskell, OCaml, F#, SML, ..) and come from a background of C, Java and Python. Go is definitely an improvement over these languages in many areas.
That said, I think a lot of what makes Go great is because of its simplicity, lack of surprises, and general lack of cleverness. You can get your hands around the language features very easily, in mere hours.
Beyond that, I think the ease of building tooling on top of the AST (or in general), the ease of deploying code to production, the build speeds, the inclusion of go get and fmt, the policies around imports and variable use (use or lose) all add up to be more than the sum of its parts. It is very obviously built by a team looking to use it in production, on real projects, as soon as possible.
Cabal used to be horrendous. Now it's just mediocre, and better than the distribution tools I've seen in the Python world (e.g: easy_install). Much better than the lack of distribution tools in the C and C++ world.
> That said, I think a lot of what makes Go great is because of its simplicity, lack of surprises, and general lack of cleverness. You can get your hands around the language features very easily, in mere hours
nil everywhere is an easy to explain language feature. It might be easier to explain than pattern matching. It's definitely worse though.
I'm not saying that Go has no strong points in its favor.
It has plenty surrounding it that you mention.
It's just sad that this is all around such a poor language.
2. Nullability IS a kind of sum... and the idea of a zero value would be impossible (or at least ruinously inefficient) without nullability. Secondly, the fact that all dereferences are checked gives you most of the same benefits, just minus all the type noise.
3. Products for errors are actually a GOOD thing, in that they allow developers to easily choose between pedantic error handling or relying on downstream panicing to handle situations that are unrecoverable anyway. Whereas with type-level enforcement, you HAVE to do all that extra checking, and that straitjacket costs you clarity and elegance.
4. Interfaces do allow for sum types, and type switch statements and/or dispatch allow for pattern matching. Not terribly elegant, but effective and understandable.
My closing thought: type systems are crutches for reasoning about the behavior of programs at compile time... and we need all the help we can get with that challenge, so yay for type systems!
At some point, however, they become cages, because there will always be a frontier beyond which they will be unable to encode contraints that are obvious to the person writing the program, and at that point, the resulting contortions will obscure, not enlighten.
What do you mean "a zero value would be impossible"? The whole idea is that sometimes you need it, and sometimes you don't, so you want your language to let you distinguish these 2 cases and then check for your program's exhaustiveness in checking it when you do have a zero value.
The fact dereferences are checked converts one runtime error into another. Proper sum types convert a runtime error into a compile-time error. How do you possibly view this as "most of the same benefits"?
3. No, they allow you to use the wrong value when there actually was an error and the value has a different meaning than intended (or just another nil dereference).
The type system forces you to have either error checking or you can use explicit type system escape hatches which are then greppable. For example, Haskell does have unsafe functions like "fromJust" which unsafely assume a result value is not an error -- but these functions are rightly considered a code smell. If you want to use them, you can, at least making the smelly parts of the code easily findable. In Go, all the code is smelly, instead.
4. Type switch statements are so clunky I don't think they can, with a straight face, be considered "effective" alternatives for pattern matching.
Consider:
myFunction Nothing = ...
myFunction (Just x) = ...
This is understandable. This is effective. Do you think the equivalent type switch in Go is?Type systems don't become cages and aren't "crutches". They are tools that you can use as much as you want. A program in Haskell can be written to be type-unsafe and put all the code in useless types. Or it can encode any amount from very little to a lot in the type system. It's just a tool you get to choose how much of your invariants you want to verify.
Go doesn't offer you that tool.
I think this accounts for a large portion of the Go<->Python talk you see.
Go is not very competitive with C at what people mostly use C for these days: tightest constraints and maximum customization. Go is very competitive with Python (& Ruby), though, as a high-productivity app development language, being almost as productive as those two but with much higher performance, lower memory requirements, and no need to install a big runtime. It's biggest shortcoming, vis-a-vis Py & Ruby, is the immaturity of its environment (libraries, toolchains, web frameworks, etc) due to its relative newness. As that changes, many will switch from P&R to Go, but fewer will switch from C to Go, because most who don't absolutely need C have already switched away from it.
Rather I now using Go in the place of Python, in situations where C was not appropriate (traditionally my hobby projects have been something C is appropriate for, or something that Python is appropriate for).
def f(a=11, b="some default", c=55.5, d=D()):
#...
f(c=44.4)
becomes type Config struct {
a int
b string
c float
d interface{}
}
func f(c *Config) {
a := 11
if c.a != 0 {
a = c.a
}
b := "some default"
if c.b != "" {
b := c.b
}
c : = 55.5
if c.c != 0.0 {
c := c.c
}
d := new(D)
if c.d != nil {
d := c.d
}
//...
}
func main() {
f(&Config{c: 44.4})
}I can't share the actual code, unfortunately, but by using struct field tags, reflect, and json, you can end up with code that looks something like this:
type FArgs struct {
A int `def:"11"`
B string `def:"\"some default\""`
}
func f(margs map[string]interface{}) {
var args FArgs
SetupArgs(margs, &args)
// ...
}
If f() is being called in a tight loop, your overhead can be enormous, but outside performance-critical code, it's probably good enough. type Config struct {
a int
b string
c float
d interface{}
}
var defaultConfig = Config{
a: 11,
b: "some default",
c: 55.5,
d: new(D),
}
func f(cfg Config) {
// ...
}
func main() {
cfg := defaultConfig
cfg.c = 44.4
f(cfg)
}
having the "keyword" arguments as a separate type
makes them potentially useful as a currency to pass
to other functions too, rather than as a set of attributes
and values defined for one function only.Test case:
func main() {
f(&Config{a: 0, b:"", c:0.0, d:nil})
}
That calls f(11,"some default",55.5,D())=> It is even harder to replicate that Python idiom (I wouldn't know how, but I have only glanced at the go language spec. It would help if you could auto-initialize structure members with values only known the the structure itself, or if one could replace that &Config above by a function call, like this: makeConfig(){c: 44.4})
Added? I think Go has less keywords than C in total.
Yes, both features allow one to escape the manifest typing present in languages like Java. But duck typing is so much more, as duck typing allows you to make shit up at runtime (e.g. come up with new interfaces based on the data you have).
By definition a static type system will reject pieces of computation that are correct when described in a dynamic type system. Also Go's static type system isn't even a good static type system, as it makes it next to impossible to work with monads or Haskell's Maybe. And serving as proof that Go's type system is weak, consider how these are non-issues in Haskell or Scala or dynamic languages such as Ruby or Clojure (yes, Clojure developers are know to use monads when it makes sense to do so).
Go's type system is a rather poor implementation of features that were properly implemented in other languages, such as Ocaml or Haskell. It's a shame really that such an awful implementation gained so much popularity on account of Google, but on the other hand I view it as a fad that will pass like all the rest.
> Structural typing is nothing like duck typing. People
> saying that don't know what they are talking about.
Structural typing is at least facially similar to duck typing. People contesting that are being pedants.The mother of all monads is Cont (http://blog.sigfpe.com/2008/12/mother-of-all-monads.html), but that belongs in the bowels of the compiler.
How well does that work with tooling? For example, in Java, I frequently ask my tools, "Give me a list of classes that implement this interface," and I expect a fast and -- most important -- 100% accurate answer.
My instinct is that Go's approach makes it tooling-unfriendly (a good chance of false positives, especially in large systems), but perhaps I'm missing something.
> in Java, I frequently ask my tools, "Give me a list of
> classes that implement this interface,"
You don't generally ask this question when working in Go, because you don't really construct your "type" system in these terms.As such you tend to see a comparison with the other language they know, which for many is Python.
Besides that, people who criticize go get's behaviour of checking out the latest revision resp. the go1 or go1.1 tag (if available) seem to forget that you're always free to populate your $GOPATH the way you like. You don't need go get for that.
Many projects maintain branches named for the Go version they are compatibile with, and the 'go get' tool automatically fetches the appropriate branch.