71 points · by bradgignac · 12y ago · 85 comments
Yes, the standard library is great. Yes, it's nice your programs compile to binaries. But what about the criticisms of the language that are always left unanswered?
I like Go a lot as a language for writing networking software. But if Go becomes the next mass adopted language for writing business applications, that will be a huge mistake for our industry.
To me, accidental complexities are quirks of design that everyone would agree to do over differently if history replayed itself. Examples like that would be:
-- Java calendar (and C Language ctime) months have index starting with 0 which means 0..11 for Jan..Dec but for days, it's index 1 which means 1..31
-- PHP inconsistencies such some functions being verb_obj while others are obj_verb and some have underscores and some do not
-- MS Excel has incorrect leap year calculation for 1900 which means all other spreadsheets must duplicate this "bug" to be compatible
Those are the types of "accidents" that arise out of ignorance or uncoordinated thinking. Andrei Alexandrescu (expert in C++ and D) has a similar concept he calls "unforced errors".
On the other hand, you compared a Tomcat servlet container as being "accidental complexity" and Go as "reduced complexity" because the http hosting is all built into the exe. To me this is an example of moving complexity around so you don't feel it for your particular use cases of the Go language.
In other words, if the Java community had a chance to do it again, I'm not convinced that Tomcat servlet would be baked into the standard Java distribution. If you bake it into the JVM, you've made the JVM Specification[1] more complex. If you leave it out of the JVM but include it as a standard class library, you've made the API library reference more complex[2] (Alternative universe: Why is the class library reference 3000 pages long?! Because it includes 200 pages to document a servlet container that most don't use.)
Complexity (in totality) wasn't reduced. It was only shifted around. I'm not saying moving complexity around isn't desirable because it is (hence we have "abstractions") but it's not an example of solving accidental complexity.
I think what happens is that we programmers find some language, or framework and if it matches our use cases, it's subjectively less complex. For the others who need generics to write algorithms, they write homegrown template code generators or resort to copy&paste which is more complex. So sure, Golang omits generics but it only makes it less complex from a language-specification perspective. However, it's actually more complex from a total project perspective. I think this explains all the contradictory posts about Django/Rails/etc being "simple" while other posts say it's "complex pulling teeth".
At this point, I don't buy that golang without qualifiers of use-cases is objectively less complex. I'm writing server-side web services with golang and for that use case, I think it's less complex than other alternatives such as C++ or Nodejs. For Windows GUI apps, using C++ with Qt is less complex than Golang.
[1]http://docs.oracle.com/javase/specs/jvms/se7/html/ [2]http://docs.oracle.com/javase/7/docs/api/
Once piece of consistent feedback that I've gotten is that I didn't do a good enough job of clarifying that I was specifically dealing with the complexity of running applications. I'm pretty sure most people who have deployed Ruby or Python web applications would agree that deploying and running those applications is more complex that it needs to be. The examples of accidental complexity you gave are great examples of how it can manifest in code design.
I really liked your last point about the importance of use cases. I briefly alluded to that in the conclusion of my article, and I'm glad that you brought it up here. Use-case is extremely important.
Where Go made things simpler is in the dependencies. The app now has all the dependencies compiled in, and so it's completely isolated from what libraries some other app in the container needed. That is a removal of accidental complexity. (Right up until you need to update all the apps to fix a bug in some library, and now you have to update each app, not just update one library in the container...)
It wouldn't be a loss if you have deleted it forever, you didn't need to keep it in your drafts.
I felt that when people say "use the right tools for the right job" and go ahead build web-app using Go, they're doing the talk the talk but not walk the walk.
I think the article's answer was: Go solves the real problems, not the academic/theoretical problems. But it's fair to ask, how does Go do that? Specifically?
The true tragedy of our industry are not the technologies we use. The tragedy is that we do not learn from prior mistakes - I was in school and into programming in the nineties and in 20 years things changed, but not that much - people are still debating basically Basic vs Pascal vs C and sometimes it feels like freaking groundhog day, the movie.
(N.B. I'm not criticizing Go here)
1. It uses null (the billion-dollar mistake) to indicate optional values. A better designed language uses an option type.
2. It has conflicting idioms for conditions. Error types use the `if err != nil` idiom while map access uses the `if ok` idiom. This means that you read the main execution path downwards and the error path to the right, unless you access a map, then the execution path goes to the right and the error path goes downwards.
3. The `:=` operator declares new variables, unless you use it to declare multiple variables where one already exists in the same scope. As a result, you don't know if you have actually declared a new variable using `:=` unless you read upwards to see if a declaration for the same variable name already exists.
val, ok := m["foo"]
if !ok {
// handle not found
}
// good path
and val, err := m("foo")
if err != nil {
// handle err
}
// good pathI'm not even sure if they need a := operator, is the additional complexity and wasted time worth the benefit (compile error on redeclared variables, most of the time)? It feels a chore having to type out := most of the time and, as you point out, confusing where there are several variables assigned at once.
Another area which is unnecessarily complex is allocation: http://golang.org/doc/effective_go.html#allocation_new
You might use:
func () (t T) {}
var t T
t = T{}
t := &T{}
t := new(T)
t := pkg.New()
t := make([]T,5)
Though the pkg.New() option is really just an optional convention. It all makes sense eventually, but do we really need all of these options? I'd rather have something like: t = T{}
t = &T{}
t = [5]T
Still, these are pretty minor niggles, which can mostly be overcome with conventions, except perhaps the use of nil everywhere, which is a shame. There's a lot to like, and the emphasis on simplicity (at the cost of features) definitely is a feature of go, even if it does have some rough edges it is significantly simpler than most other languages both to learn and to use. someString := "hello"
someString, err := ReturnStringAndError("world")
if err != nil {
fmt.Println("there's no way this could happen")
} else {
fmt.Println(someString)
}
Should produce an error.Occasionally, I wonder whether := with several variables on the left hand side should have been to defined to redefine variables (shadowing the earlier definition), but obviously the Go people thought that such shadowing would be worse.
Also, := does shadow in a sub-scope. The difference between shadowing and simply assigning in the same scope is negligible (i.e. either way you can't get at the old value).
err := foo()
if err != nil {
err := bar() // err shadowed here
}
f, err := baz() // err assigned here
What would be the difference between shadowing and assigning on that last line? You can't unshadow without leaving scope, at which point the value you were shadowing also leaves scope.2. I've never heard of `if ok` being an idiom _as opposed_ to `if !ok`.
Option types, on the other hand, are not a source of complexity, because they just use a more general language feature (ie variants). And variants aren't a source of significant complexity because they're symmetric to records (ie structs) and so emerge naturally. Symmetry inherently simplifies design by organizing and structuring things. They're a very small step beyond enums and a much saner alternative to unions.
Nils are ultimately more complex because they're baked into the language and omnipresent. And they give you very little in return! Variants, on the other hand, are a natural and relatively simple design that also vastly increases the expressive power of the language. And gives you option types for free.
That's simply not true in Go. `nil` is not an inhabitant of all types. Integers, floats, strings, arrays and structs cannot be `nil`. Slices, maps, functions, channels, interfaces and pointers are nilable.
> Option types, on the other hand, are not a source of complexity, because they just use a more general language feature (ie variants).
Go does not have variant types, so if adding option types requires them, you get an increase in the size of the language. In Go's case, variant types would have a weird interaction with interfaces, which arguably increases complexity.
Whenever you have null in a language, for every function you call that returns a reference, you have to check the documentation to see whether or not it will return null. You cannot know from only the function interface whether or not you have to deal with an optional value.
Option types move this checking to the compiler. The function declaration explicitly shows the presence of an optional value. You don't have to read the documentation or investigate the function implementation - the information exists in the function interface itself.
Given, Go tries to deal with this by using the multiple return idiom. By convention, you should only have to deal with null if you have a function with multiple returns. However, I think that compilers, not conventions, should enforce language rules. Leaving it up to conventions opens the window for human error.
> I've never heard of `if ok` being an idiom _as opposed_ to `if !ok`.
This comes from Effective Go: https://golang.org/doc/effective_go.html#maps
They explicitly call it the “comma ok” idiom.
> They explicitly call it the “comma ok” idiom
The "comma ok" idiom is the idiom of accessing maps w/ `thing, ok = m["key"]`, not the idiom of what to do with `ok` afterwards. Nothing there says to prefer `if ok {` over `if !ok {`.
---
I guess I can see a case for null-ability being more complex than not. I think the argument for them being simpler is that most of the time values are "actually" nullable (ie, the function can return nil and you should check for an error), in which case the implicit "pointers can be null" rule seems like a simpler mechanism than introducing option types (and, potentially, variant types or whatever other machinery will be needed to implement them).
As you said, the "return an err as well if the function can return nil" rule does a decent job of alleviating the complexity here. Compiler-enforced checks here seem like something that adds complexity (there's now more to the language), even if they do achieve stronger safety.
http://www.infoq.com/presentations/Simple-Made-Easy
From my personal perspective, I do not see Go achieving the kind of simplicity Rich talks so eloquently about. Instead, Go seems much more like an "easy" language.
An example of easy versus simple in the OP's article is pointing to on boarding: Sure, your on boarding of new engineers may be /easier/ because Go is an ostensibly "simple" (they actually mean small) and familiar syntax. But that does not imply any correlation with writing simple software. I would argue the difficulty of writing abstractions in Go (especially around channels) actually tends to yield the opposite!
Much like ORMs are a trap because they seem simple, so too are technologies which have such a specious quality of simplicity. It is important to establish how a given technology actually achieves simplicity in practice and I do not see how this article argues that successfully--that is not to say Go cannot achieve simplicity, but merely that this article does not seem to make a solid case, in my opinion.
Your simple/easy comparison with an ORM is a very valid one, I think. ORMs seem easy, but they're not simple, and often times their easyness at the outset causes complexity once you have to do anything that goes off the rails they've laid out for you.
But I think Go is the opposite of an ORM. There's very little magic, nothing gets done "for you". The code does what you tell it to do, no more, no less. Which means people reading the code can immediately tell what it does - it does what it says it does in plain terms.
If that is the case, the same can be said with JavaScript, Rails, Ruby yes? (all of them looked simple yet you can screw up really bad, like awfully bad, like worse than Java complexity bad).
I use ORM to do simple-to-medium complex queries enough to avoid N+1.
My ORM also have tools around it to help me generate DDL from code as part of my build (of course one still have to ensure the generated DDL is correct with proper relationship and constraints and all that jazz, but my point stands).
My ORM gives me the ability to write in either JPQL and SQL to do certain tasks like deleting a bunch of rows based on conditions. Those are handy enough.
My ORM also helps me prevent against SQL injection attack too.
How are these abilities are "traps" for me just as much as the C++ complexity are traps?
About the reference to "Go is a shop-built jig", it seems to me one way of reading that piece is that Go offloads the complexity to you to deal with, rather than offloading it to the toolchain (all the Ruby Gems, rbenv, etc stuff the author mentions). If you like to work that way then cool, but I would question the conclusion that the overall complexity has really changed.
Not great, since you're losing compile-time safety for the type -- but no worse than every single line written in a "dynamic" language like Python, and no worse than pre-generics java, say, or obj-c.
As a concrete example, take sorting. In Go, you have to implement `sort.Interface` for each custom type you define. An example taken from the `sort` package:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
}
An equivalent in Python is quite a bit simpler: class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return "%s: %s" % (self.name, self.age)
people = [
Person("Bob", 31),
Person("John", 42),
Person("Michael", 17),
Person("Jenny", 26),
]
print people
people.sort(key=lambda person: person.name)
print people
If it were just sorting, it wouldn't be that big of a deal. But there's a lot of nice abstractions missing from Go due to the lack of generics - e.g. higher-order functions like `map`.But we are doing something you can't do at all in Python (barring specialized array modules or similar).
The equivalent of the Python code would be something like:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
func main() {
people := []interface{}{
Person{"Bob", 31},
Person{"John", 42},
Person{"Michael", 17},
Person{"Jenny", 26},
}
fmt.Println(people)
SortBy(people, func(a, b interface{}) bool {
return a.(Person).Age < b.(Person).Age
})
fmt.Println(people)
}
where we have a library function // SortBy can sort anything -- just give a comparison function.
func SortBy(elts []interface{}, less func(a, b interface{}) bool) {
sort.Sort(byFunc{elts, less})
}
type byFunc struct {
elts []interface{}
less func(a, b interface{}) bool
}
func (a byFunc) Len() int { return len(a.elts) }
func (a byFunc) Swap(i, j int) { a.elts[i], a.elts[j] = a.elts[j], a.elts[i] }
func (a byFunc) Less(i, j int) bool { return a.less(a.elts[i], a.elts[j]) }
This is exactly the same, expect for instead of saying "Give me .age" like we do in Python, we have to explicitly cast and say "I'm expecting a person, give me .Age".Personally, that was the turning point when Java became palatable. Which is a shame, because Go is all-around a pretty nice language. But writing real, production code, I've felt that I was needlessly repeating myself because of the lack of generics. Specifically, I really wish I could write generics over channels, so I can solve the problems of multiplexing/demultiplexing channels, throttling them, etc exactly once.
Agreed that not having generics is a real pain-point, though not as bad as I would've assumed before using the language.
For the channel stuff, you could always just make use "chan interface{}", have your generic chan library, and then cast when receiving from the channel.
Or you could use code generation to make specific versions of your library for various types, maybe using the upcoming go generate.
It's kind of interesting, because C++ templates, for example, essentially are code-generation, but just hidden away, and for that reason tend to get overused (IMO), resulting in crazy-long compile times.
If Go's solution to generics ends up being "generate the code explicitly", it would seem uniquely Go-ish -- inelegant, but might work well practice.
(I do sort of dream about some kind of generics in Go -- something like
where X interface{}
type LinkedList X struct {
Obj X
Next *LinkedList X
}
and maybe... where X Lessable
type Heap X []X
func (h *Heap X) Push(x X) {
...
}
or even just where X interface{}
func PushHeap(h []X, x X, less func (a,b X) bool) {
...
}
Ah, to dream :)exactly.
Objective-C is essentially dynamically typed.
So it's got a static typing feel, even if it is all just dynamic method lookup at runtime.
Yes, much worse.
>and no worse than pre-generics java
That is setting the bar so low it is underground. I don't want "no worse than a language that was born obsolete 20 years ago", I want "good".
On the rare event this actually matters I use templating tools if performance is needed, but if not (which is usually the case) I use an interface. But like I said, this is so rare.
P.S. I write distributed databases / big data engines and distributed content optimizing proxy servers.
I suspect that there is as much trolling in people who complain about generics, as there is survivor bias in those who reply they haven't needed them in X years of go. If you felt that you needed them, you wouldn't have lasted long using go!
> Go isn’t perfect for every task. [...] Ultimately, it is up to you and your team to decide the best language and tools with which to build your application. While making that decision, I hope that you will take a moment to weigh the trade-offs that come with your choices.
It's a tradeoff based on your real, hard needs. If you decide that only having Array<T> and Map<T> is a deal breaker, and the complexity of creating a tool to autogenerate the go code for a large number of SinglyLinkedList<T>/DoublyLinkedList<T>/CircularLinkedList<T>/etc... outweighs the uses of Go, then don't use Go.
If you are fine writing a quick dirty code generator that can look for some <T>-like syntax and do simple replacement, or only really need Array<T> and Map<T>, then consider Go.
It's not like the language is forcing you to use it against your will.
With all due respect, but how is having to build a custom code-generator first, before you can write your actual program not accidental complexity?
Looking at the sibling comment about "go generate" by buro9, it looks like a custom code-generator won't be needed either.
EDIT: Added buro9, and emphasis
The proposal (the implementation is pretty much this) is here: https://docs.google.com/a/golang.org/document/d/1V03LUfjSADD...
If you feel a real strong need for generics, for something like a "sort by property of my custom type... do it for n types", then it's now trivial to generate that.
You can code like you have the features the core doesn't support, whilst having the succinctness, performance and maintainability that the language delivers.
I've coded Go almost daily for 2+ years and only a couple of times had the urge/need for generics... I dunno, maybe I'm the exception here.
"Probably the biggest complaint people have with Go is the lack of generics. And I did run into that in just the first couple of weeks of work on my project, and I wound up with a bunch of duplicated code to work around it. And then, when it was all working, I refactored out the duplicated code. And I refactored again. And in the end, the whole thing was simpler and shorter than what I would have done with generics. So again, in the end, Go turned out to be a language for solving real problems rather than a language filled with beautiful tools, and so you build real solutions rather than finding excuses to use your beautiful tools. Don’t try to make Go what it isn’t. If you’re trying to solve abstract CS problems in their most generalized forms, then you may find it frustrating. But if you’re trying to solve specific, practical problems in the forms professional developers typically encounter, Go is quite nice."
I'm doing that myself in a terribly hacky way using custom shell scripts and a bit of python to print out a .go file -- but seeing it in this list makes me wonder if it is a common problem that has been solved better already - does anyone know of any tools for this? (I imagine something like "bin2src -i foo.jpg -o foo.go", with support for a variety of languages)
As with Python, you still need to update code in subsequent releases to work with the breaking changes. However, in my experience, this isn't the hard part. The hard part is keeping your existing code running while staying on a recent version of your favorite language runtime. This is even more painful in an environment where multiple application run on the same server. If you write a new application using Ruby 1.9.x but an older application will only run on Ruby 1.8.x, you need to either split them across multiple servers or update the old application to run on 1.9.x. There are tools to handle this (rbenv, rvm, chruby, etc), but this is exactly the type of complexity I talk about reducing in my post.
For example, a language choice like using Python can add accidental complexity because it usually requires a container (uwsgi, gunicorn, etc..), sometimes a front-end reverse proxy (nginx, etc..), some way to package up your application and dependencies (tarballs, virtualenv, etc.). You also have to deal with deployment host issues like is Python2.6 required and available on your OS, do you have multiple apps with conflicting shared libraries that need to co-exist on the same host, do you need some system libraries installed on the hosts, are components compatible w/ each other (nginx x.y.z + uwsgi a.b.c) and can developers run that on Macs (dev laptop) and prod (linux).
I believe this is the accidental complexity the author is trying to highlight that can be avoided with Go.
I think if you look at the overall system (dev workstations, deployment envs, OS choices, CI, config management, ops, etc..), projects that use Go tend to have fewer components to manage and integrate and result in a simpler overall system.
Folks from SO gave very good explanation on why.
But because of the problem, I somehow felt cgo is like a "hack" because of the requirement that the C block code is in comments block and must be immediately follow by import "C". An additional empty line before import will cause the code build to fail.
What do you guys think?
p.s. Now I know requirement and I can live with it.
But for a full day, I have hard time figure out why my code build ok and next moment after some "cleanup" it won't build anymore. Not until I finally id the line space is real reason the build fail.
The error message also doesn't make any sense.
As a human-language equivalent, compare a jargon-laden sentence to the equivalent paragraph in Basic English. The sentence requires prior understanding of more things, but the paragraph may take a LOT of words to say anything.
"Really good software is not software that is written according to some particular design methodology. The really really good software is software that does something fabulous. Although, if you’re trying to do something fabulous it is unlikely you’d write the software in a lousy way, at least, and succeed." - pg