127 points · by xyzzy_plugh · 9y ago · 152 comments
I don't necessarily think that's a bad thing. Something that may be null is already an option type. It's "some T or null". Making the compiler force you into checking which it is, is no difference from checking for the presence of null. There is literally no difference in complexity - it's actually simpler because you don't have the cognitive overhead of remembering where a certain variable has and hasn't been null checked (After a null check, your variable has magically changed type to "some T, definitely not null".)
x = getsomething
if x != nil
dosomething(x)
and x = getsomething
if x.hasvalue
dosomething(x.value)
The programmer alone has to remember this - remember to check, and the status of each variable that can be null. Was x checked before? scroll up to see...
Add 10 variables and some nested ifs and ask the programmer which variables can and can't be null at any given place. This is the job of a compiler, not a programmer. And if my experience is any guide, the less experienced programmers, which are the ones we are discussing now, would be happy to have 100 locals or 12 levels of nested ifs in a method. They need this added help more than the people who ask for it.And I very much don't envision that the Go compiler would be modified to make sure that `x.value` is never referenced unless the presence of that value has been confirmed by an earlier statement.
The compiler enforces it by the fact that you can't pass in the return value from one thing (that might not be a valid value) into the next function that takes an argument that must be a valid value. Your objection that "but I can unwrap/call value without checking so it's useless" is a commonly raised objection - but it's a false one.
With nulls
var x = get_something
do_something(x) // ok even if x is null
With option/maybe x = get_something
do_something(x) // compiler err
x = get_something
do_something(x.value) // ok, *concious action by developer*
x = get_something
if x.hasvalue
do_something(x) // ok
The difference in safety between having to make a concius unwrap IS the whole point of the feature. This works exactly the same everywhere. You can always ".unwrap()" in Rust for example. Having to unwrap, or unwrapping without checking first isn't wrong, in fact it's often right. Unwrapping the value first means "extract the value if it exists, or otherwise panic right here". This decision to "assume success or otherwise panic" is a clear intent that the next developer can read. x = fetch_an_int // x is definitely an int
y = fetch_an_obj // y is *maybe* a T. case wrapped_foo of
NONE => ...
| SOME NONE => ...
| SOME (SOME NONE) => ...
| SOME (SOME (SOME foo)) => ...
On the other hand, with your proposed alternative, you have to create a wrapper struct for every nullable kind of thingy: type MaybeFoo struct { foo *Foo }
type MaybeMaybeFoo struct { foo *MaybeFoo }
type MaybeMaybeMaybeFoo struct { foo *MaybeMaybeFoo }
And, as if that weren't offensive enough, you have to manually pack those pointers into structs and then unpack them back.Turn the argument around. Are there any Java, C++, etc. developers arguing for the removal of these features from their languages? Are there people who say that even though these languages have generics you shouldn't touch them because they're bad? Do any devs with option/maybe types really want to go back to unsafe code that can fail if you forget to check for nil/null? Show me someone who hasn't drunk the go kool-aid who still makes these sorts of arguments and I might actually start listening.
I agree though with your initial reaction to Go and generics- it seems strange to argue not to include generics due to complexity when the alternative is either type assertions from interface{} types, code generation through some sort of [preprocessor](https://github.com/cheekybits/genny), or copy-pasting code. All of these are more complex than a simple generics implementaton! Golang could even include some sort of generics less complex than Java since it wouldn't have to worry about co vs contra variant types, and Java's generics aren't that hard to work with.
I will. Generics in Java are a net loss in my opinion. They provide marginal static safety, no additional dynamic safety, no performance benefits, and lead to substantially more complex APIs. I'd have been happier if they were never added. I would prefer a Go-like type-assertion construct or an analogous "occurrence typing" feature.
C#, on the other hand, has a sensible generics implementation that provides meaningful utility thanks to value types. However, I am not ashamed to admit that, in the absence of value types, I'll resort to Whatever<Object> plus some casts without a second thought if I find myself doing even the slightest bit of work to satisfy the compiler.
Besides, the introduction of generics has added a tremendous amount of safety to what used to be typecast littered Java code pre 1.5.
> the introduction of generics has added a tremendous amount of safety
It's added marginal _static_ safety. It added no dynamic safety. Static safety is welcome, but frequently not worth the lengths people go to achieve it. Hence my comment about instantiating generic types with Object in the event that the cost outweighs the safety.
> to what used to be typecast littered Java code pre 1.5
Occurrence typing would dramatically minimize the syntactic overhead to casting. There have been research variations of Java that accomplished this: instanceof checks insert implicit casts on branches where the instanceof check is true. Similar extensions have been explored for collections to further omit the instanceof checks without requiring explicit type parameterization. For example, if a collection is only written to privately, you can infer casts from what types are inserted in to the collection. This can achieve the same safety without massive complexity increases to sub-typing, static dispatch, reflection, type signatures, etc.
Fyi...the Google style guide doesn't ban generics/templates. It's discouraging the "template metaprogramming" which is a technique beyond parameterized types (generics) ... e.g. using recursion in Turing Complete template programming to calculate compile-time values.
If we're talking about just generics, here's example code from Google Inc's sparsehash: https://github.com/sparsehash/sparsehash/tree/master/src/spa...
It uses generic type parameters. If you ask the author if the library would have been easier and "less complex" to write if generics language feature were removed from C++, I think we'd be certain the author would say "no."
Even without asking the author, if anyone believes the library is suffers "simplicity debt" because it uses generics, they can fork the code, rewrite it, and then prove to skeptics that the hashing library was much clearer and more maintainable without generics.
Go isn't against generics, they are open to discussion about adding them if right approach to implement them without adding much of extra complexity would be found. Generics do add complexity, it is bearable in most cases, especially given the benefits, but it still exists.
Authors don't want to end up with something that C++ has, where you have to manually limit yourself in order for your code to not be too complex and unmaintainable, at the same moment, adding templates just to have them won't add any immediate benefit of large magnitude.
Turns out you can handling error like go in c++, or I should say go just used the proven working way of error handling in google c++.
Complex templates are just a type of complexity, like any complexity, avoiding them is always the right thing to do.
edit: missed a word
They also seem to admit that if they were to do it over again and start from scratch they'd use exceptions:
> Things would probably be different if we had to do it all over again from scratch.
It seems that thinking on exceptions in low-level languages is firmly in the "no way" camp.
Contrary to popular thinking, exceptions are not free.
For example, when Chrome disabled rtti and C++ exceptions in Chrome codebase, it resulted in saving 6MB (20%) of code. See https://bugs.chromium.org/p/chromium/issues/detail?id=19094
This is when exceptions where not actually used in the code. The bloat is merely from enabling C++ compiler flags to generate rtti and exception support code.
If they were really needed, then you'd have significant numbers of people trying Go and then leaving because it isn't expressive enough.
Not that that doesn't happen, but we're seeing the language gain mindshare as more people appreciate the simplicity, partly due to not having these features.
So, generics and exceptions would improve go. It just wouldn't be go anymore.
I assumed that was what the term "Simplicity Debt" was referring to.
No, but I'll bet money that there are Java, C++, etc. developers who have abandoned those languages for Go. Developers often vote with their feet before trying to change a standard.
Source: Former Java dev
- C++'s std::array is an example of marrying fixed sized arrays with templates.
- I'd say keep the built-in types and their behavior unchanged but offer a way of providing those for user types. I guess the Deletable interface is one idea but maybe the "delete" override should have nothing to do with interfaces. I think something like func (t Type) operator delete(k KeyType) ? I guess in Go a function is an interface but I wouldn't start with the interface here.
- Allowing e.g. delete or slicing on user types does not need to imply those types are polymorphic with the built-in types. This might be a little confusing but I think it's still worth while to draw that line. I don't think it's necessary to allow creating a function that takes a Deletable to take either the built-in map type or a user type.
- range support requires some sort of iterators. Could be done through co-routines like Python's generators or something more like C++ iterators? co-routines could be a cool addition to the language :)
I think you'd want to try and "contain" the change as much as possible. More syntactic sugar than fundamental changes and as little change as possible to the built-in types. Otherwise you end up with a completely new language.
What people seem to ignore is that templates are a bottomless pit of complexity.
Swift is on version 3 and they still didn't finalize the semantics of generics. Not due to lack of trying. Swift was trying to design and implement generics from day 1 and they still haven't.
That's how complicated designing generics is.
I prefer stable language with fast compiler to Swift/Rust situation, with language taking years to mature and very slow compiler. Judging by popularity of Go, so do many other people.
While the languages probably will mature after couple more years, I don't see much hope for making the compiler as fast as Go, regardless of the effort. See C++ compilers.
About one decade.
In the mid-90's already most C++ compilers had their own version of std::array, for example Borland compilers.
Robert Griesemer, a member of the Go team, has presented a similar design at dotGo 2016:
And corresponding discussion: https://news.ycombinator.com/item?id=14560471
Which is a shame. I like generics, and I implemented them in Myrddin (https://myrlang.org) for a reason.
I can't really follow the argument here: how would using option types replace the existing idiom? Instead of err being a pointer, err is an option type and the only thing that changes is that instead of writing if err != nill, you write if err. And if comparing nill vs option types works in isolation, then I also don't see where the jump to "in addition to what templated types are" comes from, or the connection to slices and maps.
In fact, if Go had option types, would it still need nill at all? By which I mean, on the user-side of things (under the hood I suppose null will be used for implementing an option). Because if it doesn't, and I strongly suspect one doesn't in a language without pointer arithmetic (which Go happens to be), then we can simply replace every nil with an option.
The discussion on how templates interact with existing features and complicate things is fairly clear, but the option types are treated as a lot more complex than they really are. In practice it is a compiler-enforced if-not-null check on pointers, because nill is a type instead of a value. That's about it. That level of compile-time enforcing also seems to be perfectly in line with the safety the Go authors want their compiler to enforce, given how strict it is with errors.
You can easily use them without really understanding what a monad is - I'm living proof of that. The only extra thing you somewhat need to understand is sum types, which are a lot simpler. Then again, Go doesn't have them and their usage overlaps with interfaces - how to deal with that might be a more useful discussion regarding option types in Go.
That has never been my impression. The main drive for generics is safer code, period. It doesn't necessarily translate to a different way of handling errors (Java and Kotlin mostly use exceptions despite supporting parametric polymorphism).
Rejecting generics because they would force a switch to monadic error handling is completely misunderstanding the value of generics, a sentiment that seems to be widespread in the Go community.
value, exists := usertype["something"]
value := usertype["something"]
func (t *usertype) operator[](k KeyType) (value)
func (t *usertype) operator[](k KeyType) (value, bool)
Should work, no?(EDIT: usertype would be the templated type, so <userType> or whatever the syntax ends up for that. so the above would be the instantiation of the template for a particular type)
if you have proper tuples and destructuring assignment, you can entirely remove that abomination.
Right now, it's impossible for a user to define a method that can return 1 or 2 values depending on how it's called.
Only stdlib types, like map and channel, get to do that.
It's fuggin horrific, and spreading that further to user defined functions would be a mistake.
Having two different functions is a way of dealing with this while minimizing change as it's just syntactic sugar and not a language change. Variable length tuple types are a much bigger change. They'd also presumably be a lot more expensive. Ideally a map type implemented by the user should be as performant as the built-in map type.
If Go had generics, the overloads could be merged into a single operator[] that returns a Maybe<ValueType>. Then that Maybe type would have an Or() method to supply a default, e.g.
doSomethingWith(collection["foo"].Or(42))
doSomethingWith(collection["foo"].OrZero())Put them together in a room, maybe they can help each other.
God forbid we'd all have to learn such a simple concept (in a language with several non-orthogonal concepts and special cases and all the channels coordination nuance that lack of generics prevents of abstracting in a standard library to boot).
>Obviously it’s not impossible to learn, but it is more complex than what we have today.
Well, adding a feature we'll always be more complex than not adding it. In the end, simple assembly style instructions are the simplest both for implementation and for learning fewer concepts as a developer. But abstractions make things easier to write and read after one has learned their concepts. And it's 2017, even "lowly" JS developers understand such functional concepts today...
>What began as the simple request to create the ability to write a templated maybe or option type has ballooned into a set of question that would affect every single Go package ever written.
This is more similar to how some molehills grow into mountains. People have been asking for generics as a standalone feature first and foremost -- orthogonal from replacing error handling. Now suddenly we can't discuss adding Generics without taking into consideration the big burden of changing the error handling too?
>On the surface this sounds like a grand idea, especially as these types are leaking into the standard library anyway. But that leaves the question of what to do with the built in slice and map types. Should slices and maps co-exist with user defined collections, or should they be removed in favour of defining everything as a generic type?
Whether the answer, the mere addition of the ability to have standard user defined generic collections and collection libraries sounds awesome in itself, regardless of what would happen to the ill-thought maps and slices that specialcased genericity in the backend.
This doesn't seem like a discussion of how to best add generics, but more like analysis paralysis.
>David Symonds argued years ago that there would be no benefit in adding generics to Go if they were not used heavily in the stdlib. The question, and concern, I have is; would the result be more complex than what we have today with our quaint built in slice, map, and error types?
A better question is: would some more complexity hurt us, especially beginning with in an overly simplistic language, and even more so, when said complexity actually unifies and harmonizes ugly special cases.
There are many languages out there that have generics. Go is build on different principals. Just use something else, no need to enforce your ideas on people who don't want them.
Maybe go users should start going into every language discussion they can find and ask for generics to be removed.
First, Go wasn't designed with "avoid Generics" as some kind of principle. That was the quick 1.0 version, but even before 1.0 it's creators have discussed (and usually post-pone to some future) the addition of generics. Russ Cox: " I don’t believe the Go team has ever said 'Go does not need generics.' What we have said is that there are higher-priority issues facing Go."
Second, it's not some "non Go users" who ask for Generics in Go. Rather the opposite: non Go users could not care less. They have their generic C++, Rust, D, Nim, C#, Java or whatever. Generics are among the most asked features from actual Go users. Sure, there are old school Go users (and most of the Golang core team) who think they're just OK without it, or not worth the trouble. But a large majority of the Go community does ask for them. I didn't pull this out of my arse (besides it being obvious if you read Go blogs and forums).
Here from the official 2016 Survey Results: "When asked what changes would most improve Go, users most commonly mentioned _generics_, package versioning, and dependency management. Other popular responses were GUIs, debugging, and error handling." (emphasis mine).
The reason why nobody is arguing that is that it's hard to argue successfully, because simple ML-style generics are incredibly useful and have negligible if any drawbacks in virtually every statically typed language.
Also, an important issue with such arguments, is that generics is a feature, so obviously it is an easy side to choose for an argument. You can either have or don't have a feature. People will instinctively select the have option because common sense dictates that it is better to have something even if you don't use it. People want to quantify an argument and having is better than not having.
People don't want to argue about language design —there are few people on the planet that could really argue about language design anyway-, they need language MHz to compare.
The more defining features are goroutines and the type system. (Structs, embedding, interfaces, ...).
Go has multiple built in generics anyway. (Slices, maps, channels), so it's not like it could be some big principle to not have them.
Generics would take away the ridiculous amounts of boilerplate that go requires, and make the language much, much nicer to use.
And safer too. The amount of `interface{}` in a lot of go code is such a smell.. always makes me wonder what the point of using a statically typed language is if you use interface{} and type casting all the time.
Curious about the race conditions being common. Is this from go encouraging go routines? Seems most programs don't need or use multiple threads for a single task.
Or show me how you would subvert Go's type system and tell me which language you're comparing it to that wouldn't allow similar type system subversion. And no moving goal posts, please. "Type safe" has a certain meaning.
The value of immutability is so overblown, as shown by literally every mainstream language being mutable by default.
Not to mention the perf cost of immutability.
For just one example see https://ayende.com/blog/164739/immutable-collections-perform... (immutable version of dictionary is 30x slower, immutable list is 16-32x slower).
I'm not cherry-picking. This is just the first search result. If you understand how immutability works from first principles, it just does much more work.
Ultimately I wouldn't describe Go as "minimizing bad programmers" but "minimizing a damage that well intentioned but ultimately mis-guided good programers can do to the codebase".
For example I believe that your enthusiasm for immutability is well intentioned but I would rather not take 30x perf hit for theoretically safer code.
Bad programmer will write a bug that can be fixed.
A mis-guided good programmer will write a compile-time parser that only he can understand (possibly only for a week after writing it), will baloon compile times, produces incomprehensible error messages and you won't be able to convince him that a standard recursive-descent parser is 10x simpler to write and read.
Go prevents mis-guided smart programmers from inflicting too much pain on everyone else.
Easy concurrency.
Good tooling.
A handy standard library.
Static compiles.
The hype of a "Google language".
You don't need "low conceptual barrier" or anything particularly beautiful about its design to explain its success.
Those are the reasons I use it too.
Good tooling in particular is available because Go syntax is deliberately simple. It's simple for humans and simple for tools.
Go shipped with Go parser in standard library from day 1. Go syntax hasn't changed from that day.
Having Go parser in standard library means that building tools like go get, linters, auto-formatters, code coverage tools etc. is very simple.
Contrast that with C++ or Rust or Swift.
A C++ parser alone (clang) is probably a bigger project than the whole Go compiler. Rust and Swift don't even have a stable syntax yet and as far as I know they don't have the equivalent of Go's ast package.
If Go didn't aggressively tame complexity then it would have ended the same way as Rust or Swift. Sure, it would have generics, but also slow compilation time, language that takes years to reach stability, tooling that is exponentially more difficult to write etc.
That's engineering: making decision about what is more important and accepting that less important things have to be dropped.
If features are most important, then you accept complexity. See Rust or Swift.
If simplicity is most important, then you accept less features. See Go.
I for one am glad that I have a choice.
I would rather have Go than a third language driven by the same ideas and priorities as Rust or Swift.
It's truly unfortunate that Haskell got the reputation of being mainly about monoids in the category of endofunctors, and zygohistomorphic prepromorphisms. The core principles are simple, solid, and lend themselves well to writing production code.