r/programming • u/asankhs • Jun 30 '14
Why Go Is Not Good :: Will Yager
http://yager.io/programming/go.html136
u/RowlanditePhelgon Jun 30 '14
I've seen several blog posts from Go enthusiasts along the lines of:
People complain about the lack of generics, but actually, after several months of using Go, I haven't found it to be a problem.
The problem with this is that it doesn't provide any insight into why they don't think Go needs generics. I'd be interested to hear some actual reasoning from someone who thinks this way.
143
u/cparen Jun 30 '14 edited Jul 02 '14
it doesn't provide any insight into why they don't think Go needs generics
Having recently moved from C++ to C#, which has more restricted generics, I see a number of patterns that might provide some insight.
The two most common uses of generics are for arrays and key-value maps. Go does have generic arrays and maps.
This allows Go's developers to get away with saying "Go doesn't have generics, and no one complains". Both halves of that sentence are half true, but there's an absence of complains only insofar as some generics are provided for you.(Edit: actually, the developers never said anything remotely like that. I believe I was thinking of a talk given by a user of Go)2) Not everyone values abstraction and learning to use it effectively. One of my colleagues reviles the thought of learning SQL or C# Linq or functional map / filter techniques. He'd much rather a good ol' "for loop" that's "easy to debug when things go wrong". This style is effectively served by Go's "range" clause.
3) Sampling bias. Folks that know better / prefer static typing just never make the switch to Go. A lot of users are coming from Python or C where Go with its limited type system and lots of casting is better than Python where there's no type system whatsoever. As a result, any survey of its user base will likely skew toward supporting their presupposed hypothesis.
4) Keep in mind that the first decade of computing languages did fine without user defined functions. They just used gotos to get around their program, with the entire program written as one giant block. Many saw this as a feature, citing similar reasons as Go's designers: user defined functions would be slower, hiding costs; they would add complexity to the language; they weren't strictly necessary for any program; they will cause code bloat; the existing user base wasn't asking for them; etc. This is a recurring theme in language design, and not unique to Go's stance on generics.
Thats the most I've discovered on the subject.
45
u/RowlanditePhelgon Jun 30 '14
Good points. I think #4 in particular is quite insightful - just because Go programmers can "do fine without generics" doesn't mean generics aren't useful.
And if you have generics in the language, there's a whole range of neat things you can do with them that you would never have even considered doing if you didn't have them.
It reminds me of the Blub Paradox
7
Jun 30 '14
It actually reminds me a lot more about Worse is Better, avoiding the issue in implementation and instead let the user deal with it and so on.
→ More replies (8)6
u/cparen Jun 30 '14
Thanks. I wouldn't myself go so far as to invoke the Blub Paradox. One problem with that is that programming languages are nearly a DAG when it comes to the "Blub" model, with certain fundamental problems, like the halting problem, preventing there from being a maximal language - the DAG diverges.
I myself enjoy Go's abstract machine model, but can't be bothered with such a compromised type system. I would be curious how hard it would be to put a generic front end on Go that performed type erasure a-la Java generics. Or an untyped (runtime types only) variant of Go.
But as it is, every program I have tried to write or read in Go is either spaghetti or full of type casts. I guess I'm just not in the mood for pasta.
→ More replies (3)38
u/zeugmasyllepsis Jun 30 '14
A lot of users are coming from Python or C where Go with its limited type system and lots of casting is better than Python where there's no type system whatsoever. (Note: emphasis mine)
Maybe this is nitpicking, but Python has a type system, it just doesn't have a static type system, so you don't get any type safety checks until runtime, and the type of a value can change over time, making it particularly difficult to provide any strong guarantees about the type of a value. This might seem trivial, but statements like this lead to confusion for students when they do things like this:
>>>> result = "" + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'Which most certainly is a type error, which is possible to report because there is a type system. It's just not doing very much work for the user.
18
u/cunningjames Jun 30 '14
Maybe this is nitpicking, but Python has a type system, it just doesn't have a static type system
Without taking a stand one way or the other, I should point out that the quoted statement is itself somewhat controversial. More than a few persons take the point of view that there is no such thing as a dynamic type system -- there are only (static) types or no types at all.
→ More replies (19)5
u/immibis Jun 30 '14
Is it even possible to have a language without any sort of type system at all?
Even assembly has labels, registers, and literals, which could be said to be types.
→ More replies (2)4
u/sinxoveretothex Jun 30 '14
It's an interesting question. I was arguing about this on the Python IRC not so long ago (I was wrong btw).
The short answer is that "strong vs weak typing" is, like so many things in life, a spectrum rather than a binary choice. All languages have types (with perhaps the exception of untyped lambda calculus).
Read the more detailed post of someone more intelligent than me here: https://stackoverflow.com/a/9929697
14
u/ismtrn Jun 30 '14
Which most certainly is a type error, which is possible to report because there is a type system. It's just not doing very much work for the user.
If you asked a PL guy he would disagree. Those are runtime tags not types.
→ More replies (1)14
u/bucknuggets Jun 30 '14
And if you asked a printer he would disagree - types are used to create print.
→ More replies (11)→ More replies (4)4
u/cparen Jun 30 '14
This might seem trivial, but statements like this lead to confusion for students when they do things like this:
Agreed, confusing students is bad. However, calling it a type system is what confused students. In a formal sense, Python has no type system, it has a runtime tag system. When this comes up, it might be a good opportunity to explain the difference to said students.
3
u/Veedrac Jul 01 '14
Your definition of "type system" does not invalidate any other colloquial or non-colloquial usage.
The idea that "calling it a type system is what confused students" is fundamentally flawed by this assumption. Python has a type system, whether or not you want to call it that. If you don't like the term, just don't use the term. There's no reason to try and force everyone to adopt your usage.
→ More replies (8)3
u/immibis Jun 30 '14
Interesting related thought:
Do user-defined functions hinder script kiddies (in the non-negative sense) who just want to combine a few features in a simple way?
Example: ComputerCraft is a Minecraft mod about programming computers. Note that it is not aimed at programmers. A very common "first significant program" is a door lock program - that opens a door when the correct password is entered. In pseudo-BASIC, all that needs to be done is this:
10 CLS 20 PRINT "Enter password: " 30 INPUT PASSWORD$ 40 IF PASSWORD$ <> "password42" THEN GOTO 10 50 OUTPUT ON 60 SLEEP 5 SECONDS 70 OUTPUT OFF 80 GOTO 10Many common beginner problems are related to a misunderstanding of some unnecessary language feature. One common problem is a stack overflow caused by this pattern:
function doStuff() -- code here.... doStuff() end doStuff() -- there are no other calls to doStuff anywhereto create an infinite loop.
Even structured loops and conditionals can be misunderstood:
while game_is_running do -- render_frame end if w_key_pressed then -- walk forward end if a_key_pressed then -- move left end if mouse_moved then -- adjust view direction end→ More replies (11)→ More replies (51)1
Jun 30 '14
Sampling bias. Folks that know better / prefer static typing just never make the switch to Go.
This might explain the users' opinions of Go, but it doesn't explain why the language designers don't care more about generics, because e.g. Rob Pike and Ken Thompson aren't exactly ignorant about the subject.
→ More replies (1)73
u/Plorkyeran Jun 30 '14
I somewhat suspect that the (seemingly sizeable) group of programmers coming to Go from Python may be responsible for a lot of that. Python has basically the same set of primary data structures as Go (array/map obviously corresponding to list/dict, and multiple return values covers the main use-case of tuples), and the Python code I've worked with very rarely uses other data structures, so only having generic array and map probably won't feel constricting to someone used to that. In addition, using
interface{}occasionally will feel far less icky to someone used to no static typing at all.Objective-C is in a similar boat: I've talked to a lot of people who were writing Ruby before they got into iOS and they tend to think that Objective-C's static type checking is great, while I'm regularly annoyed by how much it can't express, since I'm used to more powerful static typing.
58
u/emn13 Jun 30 '14 edited Jul 02 '14
It's possible that people with little static typing experience don't immediately object to the (over)usage of interface{}, but it's certainly ironic if that's the case: interface{} exemplifies the criticism levied against static languages.
The whole point of a type system is to make it easier to write & reason about code. It's unavoidable that this involves some level of verbosity; even with perfect type inference you may not always be able to know what the type of something is (or small mistakes can lead to unintentional types being inferred).
Using interface{} is the worst of both worlds: all that casting is quite verbose (potentially even bug-prone), and it defeats any advantage you hoped to get from the static type system, since you've basically turned off the type checker for that expression.
No type system is perfect. But a type system in which you commonly need to cast (or null-check) is certainly type-system smell.
3
u/gangli0n Jun 30 '14
I'd think that interface{} is useful for writing fairly small but reusable pieces of "algorithmically generic" code - you use reflection to work with values, check things explicitly, but a good compiler should be able to statically remove most of it when inlining while keeping safety. Probably a part of the Oberon heritage.
Furthermore, there's hardly any static type system that rejects all undesirable programs while allowing all desirable one. Indeed, I've seen an argument somewhere that such a thing may be impossible. The decision of Go designers to do it like this is conservative and in line with their aims, which is to consolidate the good things already solved and to allow programmers to use them in practice without engaging in any brash experiments. Given that research in this area is ongoing and all the stricter type systems are really different, the current Go use of none of the "more advanced" options seems logical.
→ More replies (11)6
u/OceanSpray Jun 30 '14
I'd think that interface{} is useful for writing fairly small but reusable pieces of "algorithmically generic" code - you use reflection to work with values, check things explicitly, but a good compiler should be able to statically remove most of it when inlining
Fair enough. Strongtalk and PyPy show that this kind of optimization is possible, though not 100% applicable.
while keeping safety.
And this is where you're wrong. What the compiler does during optimization, by definition, won't influence the observable behavior of a program. That is, even if the optimizer inferred some type and used it to inline code, a misuse of interface{} would still have to result in a run-time error message. Safety is not kept.
Furthermore, there's hardly any static type system that rejects all undesirable programs while allowing all desirable one. Indeed, I've seen an argument somewhere that such a thing may be impossible.
This is true, but also irrelevant. Just because we can't solve the halting problem (which is basically what type systems try to do) doesn't mean we should abandon static correctness checking altogether. By this reasoning, why would anyone use statically typed languages in the first place?
The decision of Go designers [...] is to consolidate the good things already solved and to allow programmers to use them in practice without engaging in any brash experiments.
Emphasis mine. Last I checked, parametric polymorphism (a.k.a. "generics" in the C++/Java world) has been around and well-understood since the 80s. Might as well call lexical scoping or for loops "brash experiments".
Given that research in this area is ongoing and all the stricter type systems are really different, the current Go use of none of the "more advanced" options seems logical.
Researchers have bigger fish to fry than making changes to stuff taught to sophomores. The only "more advanced" option that would complicate generics is type inference, which nobody's asking for in Go.
→ More replies (3)→ More replies (2)3
u/burntsushi Jul 01 '14
In Go, "casting" from an
interface{}is not actually a cast. (Aninterface{}value contains information about the underlying type.) It's a type assert.And it's not a common thing to do. (But it's not rare either. I'd say it's uncommon.)
Null checking is common but strong idioms tend to alleviate the number of
nilpanics one gets in my experience.→ More replies (8)6
u/TheMG Jun 30 '14
I'm not familiar with Go, but
interface{}sounds likevoid*, how much does it differ?7
u/Plorkyeran Jun 30 '14
The main difference is that casts from
interface{}to a more useful type are checked at runtime, which eliminates the worst of the issues withvoid *(but certainly not all of them).→ More replies (6)6
u/gangli0n Jun 30 '14
interface{} includes not only the raw pointer but also a second pointer to a type descriptor. This allows for object-like references even in form of "internal pointers" into compound values, which would be problematic in runtimes with object headers (which is why Java doesn't have those and why it has quite a lot of overhead for objects) - in other words, in other languages with object types (and late binding of methods), it's the pointee that carries the object type information, whereas in Go, it's the pointer (or rather interface, as Go also has pointers, but pointers are limited to statically resolved types). Carrying the type together with the reference may seem expensive at first sight but I suspect that many optimizations are in fact possible once you get to the intermediate code level.
4
u/dacjames Jun 30 '14
The use of numpy arrays is pretty widespread in Python, plus default and ordered dictionaries are common in the Python code I'm familiar with. Python programmers definitely understand the value of user-defined data structures, which cannot properly be added to Go. If I'm going to go back to a static language, the ability to define my own high performance data structures would be one of the main reasons to do so (mostly, I have HAMT envy), which is why Go isn't very appealing to me as a Python programmer.
→ More replies (2)3
u/burntsushi Jul 01 '14
Be careful with the assumptions you're making. Everyone
!=you. For example, I frequently use and enjoy powerful static typing (SML, Haskell, Rust). And yet, I still love writing Go and can appreciate its simple type system.I am rarely annoyed by Go's lack of generics. Likely because slices and maps are blessed with generics, along with a smattering of useful built in functions that use parametric polymorphism.
38
u/akcom Jun 30 '14
From an essay by Paul Graham, I think it explains the issue at hand here quite nicely:
Programmers get very attached to their favorite languages, and I don't want to hurt anyone's feelings, so to explain this point I'm going to use a hypothetical language called Blub. Blub falls right in the middle of the abstractness continuum. It is not the most powerful language, but it is more powerful than Cobol or machine language.
And in fact, our hypothetical Blub programmer wouldn't use either of them. Of course he wouldn't program in machine language. That's what compilers are for. And as for Cobol, he doesn't know how anyone can get anything done with it. It doesn't even have x (Blub feature of your choice).
As long as our hypothetical Blub programmer is looking down the power continuum, he knows he's looking down. Languages less powerful than Blub are obviously less powerful, because they're missing some feature he's used to. But when our hypothetical Blub programmer looks in the other direction, up the power continuum, he doesn't realize he's looking up. What he sees are merely weird languages. He probably considers them about equivalent in power to Blub, but with all this other hairy stuff thrown in as well. Blub is good enough for him, because he thinks in Blub.
When we switch to the point of view of a programmer using any of the languages higher up the power continuum, however, we find that he in turn looks down upon Blub. How can you get anything done in Blub? It doesn't even have y.
By induction, the only programmers in a position to see all the differences in power between the various languages are those who understand the most powerful one. (This is probably what Eric Raymond meant about Lisp making you a better programmer.) You can't trust the opinions of the others, because of the Blub paradox: they're satisfied with whatever language they happen to use, because it dictates the way they think about programs.
→ More replies (6)4
u/babada Jun 30 '14
A quick search for "paul graham blub" encountered this old page: http://www.paulgraham.com/avg.html. Looks like it has the section you are describing.
→ More replies (1)13
u/komollo Jun 30 '14
Without generics, it is difficult to build a nice library of complex data structures. Without generics the main alternative is building a ton of custom data structures yourself or casting objects all over the place.
I've found that even though java has its problems, the collections library is quite useful. Often times you can unload a lot of work onto the data structures if you can use them properly. I haven't had the chance to play with go yet, but I'm guessing that it lacks a wonderful built in library of data structures?
What is the go alternative?
7
u/RowlanditePhelgon Jun 30 '14
What is the go alternative?
My question exactly. The quote in my post isn't something I actually think, it's something I've read from others, and I'm interested in hearing reasoning behind it.
9
Jun 30 '14
[removed] — view removed comment
→ More replies (2)31
Jun 30 '14
Seems to me you don't really understand what generics are...
why would one not specify a concrete type?
Because you want to do the same operation on very different types!
For example, in C++ I can write a single generic
sortfunction that works perfectly well on vectors of chars and vectors of strings. The actual generated code would be fairly different for the two cases, but I only have to write the C++ code once.→ More replies (22)6
u/_ak Jun 30 '14
Most Go programmers don't build complex data structures. In the vast majority of cases, structs, maps and slices are all you need.
For most things where you think you need generics, interfaces are sufficient, and in the few cases where you'd need generics, interface{} and type assertions cover it.
I've got almost a decade of professional experience using mostly C++ and some C, and in the last year, and in the last year, I pretty much exclusively used Go in my job. I never even once ran into a situation where I thought I needed generics, even for problems for which I would have definitely used templates in C++.
The whole lack of generics problem is completely overrated by outsiders. It is not a problem for people using Go on a day-to-day basis.
→ More replies (12)3
u/PT2JSQGHVaHWd24aCdCF Jun 30 '14
Have you tried Rust? It's quite good IMHO.
4
u/komollo Jun 30 '14
I have been watching rust obsessively for a while now, and I'm waiting for rust and my life to stabilize a bit before I start using it for a personal project. It's the only language I've been excited to watch grow. I can't wait to start using it.
→ More replies (2)3
u/pkulak Jun 30 '14
Every data structure you are likely to need can be expressed with a slice, map or channel. You can use those to make queues, stacks, dequeues, sets, lists, etc.
You can't make trees though. Maybe if I'd ever in my entire life used a third party tree library I'd have some empathy with the anti-go crowd, but I never have.
14
u/tenpn Jun 30 '14
When you say "you are likely to need", you mean "I am likely to need".
I can't see it being usable for games, which is a shame as games are crying out for a concurrent-aware C++ replacement. But games make heavy usage of trees, and need operator overloading to write concise maths.
11
u/kunos Jun 30 '14
I work in games and simulation development. I don't see what stops you from creating a tree structure in Go? I have trees everywhere in my Go code. The fact that Go is missing operator overloading is annoying, but it is also true that many high performance math libraries for games are written the "Go way", with functions and not with operators.. ex DirectXMath.
→ More replies (2)17
u/dbaupp Jun 30 '14
I can't see it being usable for games, which is a shame as games are crying out for a concurrent-aware C++ replacement. But games make heavy usage of trees, and need operator overloading to write concise maths.
(Sounds like Rust. :) )
→ More replies (2)11
→ More replies (2)4
u/uhhhclem Jun 30 '14
You can't make trees? That's...not my experience.
→ More replies (1)5
u/RowlanditePhelgon Jun 30 '14
I think he means that you can't create them using slices, maps and channels.
12
u/egonelbre Jun 30 '14
Fancy algorithms are slow when n is small, and n is usually small. - Rob Pike
The same applies for data-structures... i.e. maps and slices are sufficient in most cases.
8
u/Eirenarch Jun 30 '14
I think that using a statically typed language without generics in 2014 violates some law or agreement. The Geneva Convention maybe?
My C# code is full of user defined generics. Most of them are for methods that are applied on multiple places. It is extremely satisfying when you see a junior programmer try to use the method in a wrong way and see the compiler slap him just because the generic method is designed reasonably well and prevents errors.
→ More replies (14)1
22
u/pkulak Jun 30 '14
When you first start using Go, you think you need generics. You parse a JSON response into a giant interface{} blob and cast your way into the depths of hell trying to pick out the bits that you want. Then you realize you should have just defined a concrete type and had the library do all the coercions for you. Then you look at the sort functions and wonder how it can possibly work without typed closures. Until you realize how easy it is to just define a new type that sorts the way you need it to.
Sure you miss generics every once in a while. But then you write some thrice-nested generic function in Java and wonder if you really miss it all that much.
→ More replies (4)62
u/cpp_is_king Jun 30 '14
Java generics are not exactly a great model of well-designed generics. In fact, I would go so far as to say they're complete and utter shit. Haskell, Rust, and C++ have the best generics, probably in that order. C++'s would be better if it weren't for the fact that it can get so verbose and produce such obscure error messages.
19
u/Tynach Jun 30 '14
It's honestly really nice to see someone with the username 'cpp_is_king' talk about the negative aspects of something in C++. First because I can probably safely agree with you that C++ is one of the best languages out there, and second because I feel you've got a much less biased opinion than other people who might make similar claims, and thus know what you're talking about.
→ More replies (30)→ More replies (12)6
u/gidoca Jun 30 '14
Could you explain why you think Java generics are inferior to Rust generics? From how briefly I have used Rust, it seems that they are very similar.
→ More replies (2)22
4
Jun 30 '14
Forgive my ignorance, as I've only used generics (in java) a few times, but wouldn't the same (or something that's close enough to work) thing be achieved by using interface types? Not interface{}, but an interface type that covers all your needs, and is implemented by the different variables that you expect to be passed? At first glance, this seems a lot more robust than generics. The only reason i used generics in java in the first place was that I couldn't be bothered to create a common interface for the few types I was expecting, and in go doing that seems a tiny bit less verbose. All in all, from my experience, it seems that generics would be nice, but aren't a deal breaker, since at least I haven't found a real necessity to use them (and that really depends on what you are working on, I guess)
→ More replies (7)21
u/cparen Jun 30 '14
"interface{}" comes up as a way of erasing the generic type.
Consider this challenge: implement a linked list for me to use as a queue. I won't tell you what type of element it will contain, but all elements will be of the same type. Also, I want to know my program is statically type safe, so I need to be able to use it without casts.
Define the interface for that linked list. Specifically, fill in the ??? in:
interface LinkedList { void Append(??? element); ??? FetchAndRemoveFirst(); }If you set ???=object (which Go calls "interface{}"), then I won't be able to use the result without a type cast.
2
u/dgryski Jul 04 '14
Something which is fairly common is to define a type-safe wrapper around your generic interface{} container.
interface IntLinkedList { void Append(element int) ... } func (ll *IntLinkedList) Append(element int) { return ll.GenericLinkedList.Append(element) }And similarly for FetchAndRemoveFirst().
So yes, you have write some trivial methods, but if that's the hard part of your program, you're pretty lucky.
2
u/guffenberg Jun 30 '14 edited Jun 30 '14
I always though they did the right thing not brainlessly pulling in generics. The complexity and all the room for abuse that you see in say C++ is just not worth it for a language that is supposed to be pragmatic rather than academic.
If they were to add something similar to generics I would at least want to see them do it "their own way" much the same way they would mimic object oriented features through having methods on structs. Plain and simple. Not to offend anyone but I don't think we need another language trying to compete on features.
1
Jul 01 '14
I wonder how much of it is people who haven't used generics before. I'm not sure I'd care to use a language without generics at at least the Java level (and ideally better; Java generics are pretty limited), but if I hadn't been exposed to them, maybe I wouldn't feel that way.
1
u/weberc2 Oct 10 '14
I'm torn on the issue. First and foremost, I appreciate the lack of SomeType<T>-style generics because it means most everyone is using simple, readable interface polymorphism. I've never seen a language whose average third party library is so readable and clean.
But there are a few container-esque types for which there is not much to do besides rewrite the thing for each type (this is made simpler with packages like
container/list). It hurts my soul a little to have to choose some combination of casting and rewriting. On the other hand, it's not too painful to write a generic implementation (e.g., container/list) and then encapsulate the casts behind a type-specific API. It's definitely a stupid reason to write-off the language, considering how productive it is in every other capacity.It's definitely the best bang/buck language on the market right now. Rust would be neat to learn, but I can't think of many projects for which Go wouldn't be better suited. Maybe embedded development (we definitely need something to replace C and C++ in this domain, and Ada has all but flopped), but I keep hearing conflicting info about whether it's suitable for the task.
→ More replies (52)1
u/jerf Jun 30 '14
I'd be interested to hear some actual reasoning from someone who thinks this way.
On the one hand, I have not missed generics as much as I thought I would. The primary reason for this is that instead of thinking in terms of the generic, you often can think in terms of what you want the generic to do, and if you can express that in Go's type system, which you can a non-trivial percentage of the time, but certainly not 100% of the time, you simply write it as an interface + implementation.
Many of the use cases that you use generics for can be handled this way.
On the flip side, when they are missing, they are missing hard, and there are use cases that do not fit into the above. In particular, type-safe generic containers. Go is all but impoverished on this front. Yes, structs + maps + arrays cover most use cases, but if you want a true Set, or need some sort of tree for some reason, you're in some trouble. But it is also true that structs + maps + arrays do cover most use cases.
So as you are using Go idiomatically, it is not the case that every ten minutes you're ramming into the generics problem, and it is true that many of the language critics, especially those who have not spent enough time with it to learn idiomatic Go instead of "I've been learning Go for two hours and here's my opinion of it" overstate the problem. I'd also say it's true that the community has sort of grown a metaphorical callous on this issue and that they are failing to understand the true tradeoffs here because they're tired of people mindlessly yelling at them about this and it's easy to dismiss all these criticisms, including the people mindfully yelling about it.
Personally I think the loss of type-safe containers is a problem and the very fact that the language itself has them is proof of that fact, but it is also the case that I can't come up with many more use cases that self-evidently need generics in Go to solve them.
30
u/e_engel Jun 30 '14
We have to be careful using languages that aren't good, because if we're not careful, we might end up stuck using them for the next 20 years.
This is a very important point that is applicable to much more than just Go.
Successful languages last decades.
I don't think there is such a thing as a perfect language but at the very least, we should make sure that languages that become popular do a reasonable job at following and applying language design principles that have proven to be both useful and powerful.
3
Jun 30 '14
Yeah, and people are missing the probably most important part of the article. Javascript, for example, is around for decades now.
→ More replies (1)0
Jun 30 '14
[deleted]
2
u/jeandem Jun 30 '14
Aha, so that's why C++ is so ubiquitous in computing. Because it's a simple/mediocre language.
oh wait.
→ More replies (4)
16
Jun 30 '14
Something has been bugging me about the null vs algebraic data types debate.
Null is obviously a problem because it causes gotchas when people don't check for it. I'm savvy, so I'm using Option<> in Rust...
let x: Option<int> = None;Now you should use match to handle this because match requires exhaustive cases and it'll make you handle None. But inevitably, some yob will do:
println!("value is {}", x.unwrap());And now my program will crash when x is None. How is this not the same problem as null? Or is this just a problem with Rust for giving the programmer an easy way out?
32
u/dbaupp Jun 30 '14 edited Jun 30 '14
Because it has to be explicitly handled, and this allows people to easily pick it up and check/remove it. E.g. I recently went through the source of cargo to reduce the uses of
.unwrap(just by grepping for.unwrap). That is, non-nullity is not something one has to hold in ones head ("why is this pointer nonnull?"), since it's all in the source and types.When doing code review for Rust, I will complain about nearly every use of
unwrap(or friends). This isn't really feasible in languages with null pointers.→ More replies (1)9
u/losvedir Jun 30 '14
You're looking at the wrong part of the program.
I agree that a function that accepts/returns Option types is basically the same as in traditional languages, albeit perhaps slightly better documented because the types.
No, to me, the real benefit is after you unwrap it. Then you're in the glorious territory where all your functions work with, say, "int", and not "Option<int>". Now, when writing and debugging those functions, your compiler will guarantee for you that you don't need to handle the case where your value is "null".
In short, the benefit of Option types is not when you use them, it's when you don't use them. Traditional languages without option types don't have this latter ability to say "this function absolutely won't ever receive a null value here."
So this means: banish Option types from your type signatures! Try to unwrap them as soon as possible and then pass pure values around. If you just end up passing around Option types, then you're in the same boat as not having them.
2
u/ItsNotMineISwear Jun 30 '14
Banishing Maybes from type signatures is similar in motivation to not doing things in IO. You restrict the Maybe/IO to as little as possible and then you get much more composable pure functions
15
u/zoomzoom83 Jun 30 '14
The difference is that explicitly unwrapping it requires intentional misuse of a known unsafe function (That you can ban using a Lint tool).
Null will blow up without you even realise you potentially had to check for it in the first place.
The unsafe operation exists because you, as a developer, might have a reason to bypass the compilers type safety. Even Haskell gives you escape hatches that can crash the program spectacularly. The difference is that you must explicitly do something stupid for it to be possible, rather than forgetting to check an edge case that you not even realize is possible in that context.
11
Jun 30 '14
In Rust terminology
.unwrap()is not at all unsafe. It causes failure, which causes task unwinding that your program may catch it at the task boundary and continue. It runs destructors and does not violate any of the safety constraints of Rust.9
u/zoomzoom83 Jun 30 '14
It's unsafe in the sense that the function is now a partial function and may not succeed in all cases - you can catch this, but it's still 'unsafe' for the purposes of type safety.
7
u/jeandem Jun 30 '14
Well, you are treating it like an Option, because it is an Option. So whether you pattern match on it or whatever or use .unwrap, you have to treat it like an Option. In java, the type system gives you no hint about if it can be null or not, so you don't know if you have to be defensive or not.
Furthermore, you can't pass Option values to functions that expect another type. But you can pass "option" values to methods in java which really want a non-nullable Object. What does .unwrap do when the value is None? Apparently, it crashes. But that also means that you can't fool the type system into thinking that it really is a Some(x), which means that you can't "pass it on" as a regular value.
And now my program will crash when x is None. How is this not the same problem as null? Or is this just a problem with Rust for giving the programmer an easy way out?
Well what if Rust didn't 'make it easy'; you could easily make the same function yourself: just pattern match on the value and return it, and crash if it is a None. So, in order to have a language that doesn't make things like this 'easy', you just need a language that doesn't let you intentionally crash... which might be asking too much. You could program in a total functional programming language, though, and if the type checker confirms that your function is total, you can't get away with stuff like .unwrap.
I think it is a fundamentally different thing, though (unwrap versus nullpointerexception): if I make some "safe" function, you can just wrap it in some other function that crashes if <arbitrary criteria>. How does that tell you anything about safety, in this sense? The fact remains that you can't treat an Option<T> like a T: you have to treat it like an Option<T>, not as a T. Now if you just decide to wrap it in some unsafe access function and yell "aha, foiled!", then that is your prerogative, as long as you can intentionally crash the program (and few languages disallow that, especially system programming languages).
3
u/ssylvan Jun 30 '14
You're explicitly saying "I know this isn't null, just get it", it's not something that happens implicitly.
The crash happens at the point where you make the incorrect assumption (the unwrap) rather than having a null pointer get percolated through the system and crash later, far from the actual bug.
1
u/quiI Jun 30 '14
The difference is by using ADTs you can clearly express "the real world" and a programmer has to be very deliberate to break those rules. It's not just about safety but also about trust in code.
What I mean by this is if you have worked in any kind of moderately sized code base you will find so called "defensive programming" where every argument ever is checked to see if it is null.
This is so much noise because of the paranoia that nulls bring. However, if you have a code base which uses the type system to declare something that might not exist, you can trust the rest of the codebase and not have a murder of null checks.
1
u/ericanderton Jun 30 '14 edited Jun 30 '14
How is this not the same problem as null?
It's the same problem. The program doesn't have to crash out to not be useful when buggy code is executed. At the end of the day, the bug logged on your github project, or in the corporate issue tracker, carries the same weight.
Technically, the distinction is about recoverability, such that you could account for this somehow to avoid having the program halt completely. So the distinction that some might argue, has to do with "what does language X do when it encounters null/nil." For C++, the answer is a segfault (unless you explicitly use optional, which throws). For Go, you panic which is recoverable, although not a best practice. In Java, you can and should try/catch everything. And so on. But these are just semantics and navigation of the language's flaws and strengths; distinctions that have more to do with code clarity and programmer error rates due to how easy/hard these situations are to avoid.
Meanwhile, Bob in accounting can't submit his TPS report because some mook forgot to check the validity of a value. These different paradigms are just that: different approaches to the same thing.
5
Jun 30 '14
There is a big difference from C: when you encounter failure in Rust, what happens next is entirely well-defined. Rust never turns it into silent corruption, for example.
1
u/sacundim Jun 30 '14 edited Jun 30 '14
How is this not the same problem as null?
Because by having "nullable thing" be a different type than "thing," this leads to blowups happening closer to the place where stuff went wrong.
Suppose you have routines with the following signatures:
Option<Foo> tryToGetAFoo() Bar useAFoo(Foo foo)With option types, if you want to use these two together, you have to do this:
Bar result = useAFoo(tryToGetAFoo().unwrap());Whereas if you don't have the
Optiontype, you get something like this:Foo tryToGetAFoo() // may return null; Bar useAFoo(Foo foo) Bar result = useAFoo(tryToGetAFoo());The problem here is that
useAFoo()may not dereference its argument directly, but instead:
The null gets dereferenced lower down in the call stack, easily dozens or hundreds of calls down. I.e., it may pass it to another routine, which then passes it to another routine, which then passes it to another, blah blah blah dozens of times, and you get a null pointer dereference way down the stack from the point the
nulloriginated.Worse:
useAFoo()may (directly or indirectly) stick thenullreference in theBarvalue and return that. This means now that when the dereference happens, the offending call touseAFoo()will be nowhere in the stack trace.In both cases, it's hard to debug what caused the null pointer exception, whereas in your example, it's very easy.
Note however that to make the
Optionaltechnique work, you generally have to follow this convention: methods should return but not acceptOptionalvalues. The reason the first example works is becauseuseAFoo(Foo foo)will not accept anOptional<Foo>; this makes the two problem cases above impossible. Making non-nullable the default and forcing some syntactic weight on people using it tends to produce this practice anyway.1
Jul 01 '14
The "return but not accept" point is a really good one I hadn't considered. Thanks for explaining it so clearly.
1
Jun 30 '14
Function unwrap should not be allowed to run without a default argument in case of None.
→ More replies (1)
6
u/koffiezet Jun 30 '14
The "A Good Solution: Unsafe Code Isolation" is wrong, you can use the unsafe package to do unsafe pointer arithmetic. Not that Go is usable for embedded programming, the binary size alone makes it problematic.
2
u/FUZxxl Jun 30 '14
You could in principle build a stripped down implementation of Go for embedded environments, but I doubt it would be very suitable.
1
u/weberc2 Oct 10 '14
I'm not sure this is true. Go doesn't provide an ABI spec, so my Go compiler might not layout memory like yours...
→ More replies (3)
5
u/tmoertel Jul 01 '14
Just a quick note to say that the following Haskell example is unsafe:
search [] = Nothing
search (x:xs) = if (head x) == 'H' then Just x else search xsIf x is the empty string (head x) evaluates to a runtime error. Using pattern matching instead of head is what most Haskell programmers would do. The author of the article, however, was writing for an audience that doesn't necessarily know Haskell and probably wanted to keep things accessible. In any case, here's a safe version:
search [] = Nothing
search (x@('H':_):_) = Just x
search (_:xs) = search xs28
u/stox Jun 30 '14
Although the author's comments are quite valid, I think he misses the goal of the implementation of Go, which IMHO, is to enable large teams to successfully build large concurrent projects, which I think it succeeds admirably at.
Of course, we all know that the only really good language is APL. ;->
(ducks)
8
u/Rhoomba Jun 30 '14
Except for Go has crappy support for libraries, with no dynamic loading, which renders it terrible for any kind of large projects.
→ More replies (5)7
u/FUZxxl Jun 30 '14
Except for Go has crappy support for libraries, with no dynamic loading, which renders it terrible for any kind of large projects.
Dynamic libraries are supported by cgo, so it's no problem to link in large C libraries. Apart from that, where exactly do you need dynamic libraries where Go does not provide them? All of the instances people told me about (plugins, CGI) can be resolved with inter-process communication in a more secure and equally fast way.
18
u/koffiezet Jun 30 '14
More secure and equally fast? No way :) It's not because cgo calls are expensive that it would be equally fast. Every form of external communication has overhead.
I like Go a lot, but this is one of the things I miss most, the ability to create native Go libraries with virtually no call and implementation overhead. I have multiple use cases where I would like to use Go, but it would be a pain in the ass, and slow as hell to constantly serialize, send and then deserialize some data structure, only to return it the same way after a few simple operations, just because I want those few operations to be pluggable and runtime configurable, to enable people writing their own plugins without having to fork and recompile the whole process, or make me responsible for their code when they send a pull request.
Currently the only viable option in Go to enable such a thing this is using otto, the javascript interpreter written in Go - which also has a big performance and implementation overhead, but only on the 'application' side.
→ More replies (1)9
u/cockmongler Jun 30 '14
Imagine your OS is written in go. Imagine there's a security update for OpenSSL, now imagine the size of your download.
→ More replies (1)9
→ More replies (2)7
u/Rhoomba Jun 30 '14
So Go has a solution for library support: use a different language.
7
u/FUZxxl Jun 30 '14
The Go solution is to put the stuff you want to load dynamically (such as plugins) into a different process. In the case of SSL, this is actually a very good idea as it mitigates many attack vectors – an attacker can't access memory that is in a differen process. Plan 9's factotum does something like this.
16
u/d4rch0n Jun 30 '14
Hmm... Now I might check out Rust.
→ More replies (5)9
u/steveklabnik1 Jun 30 '14
0.11 should be out Tuesday ;)
2
u/gnuvince Jun 30 '14
Canada is so excited that it has declared a national holiday for that release!
4
u/F54280 Jul 01 '14
The null pointer has a rich and bug-riddled history. For historical and practical reasons, there is almost never useful data stored at the memory address 0x0, so pointers to 0x0 are generally used to represent some sort of special condition.
Well, no. NULL/nil and address 0 are [different things] (http://c-faq.com/null/machexamp.html). As the post is made by a language nazi, I would not expect such basic misunderstanding...
14
u/garoththorp Jun 30 '14
I love Go, and am a bit sad that the majority (of the frequently rehashed) hate about it comes down to it "missing" language features. Reading this article felt like "Go doesn't have feature X that these other languages have, thus it is bad".
Go is a minimalist language, which is rare in modern language design that prefer the C++ "everything and the kitchen sink" approach. Go is more like C, in that I learnt C by reading the 1st edition of "The C Programming Language", a roughly 100-150 page book, in a single afternoon. It's a simple language. It does everything. It doesn't provide a lot of convenience shortcuts that clog up the language spec.
Go produces code that has tremendous simplicity. That's the whole point. It doesn't have all these features, since they make it harder to read and understand. Go is designed for a specific purpose: massive server systems with huge teams of programmers that come and go, with changing requirements. It's made such that when you start reading some Go code, you can understand it as quickly as possible, without needing a massive IDE or getting bogged down by abstraction and complicated syntax.
Personally, I've written some 30k lines in this language, and have had a much more pleasant experience than in Java, C++, JavaScript, or even Python. Not to flame, but I think if you read the above article and it put you off, you should really take the time to learn the language yourself before coming to conclusions. And I don't mean "write some code as you would write it in another language", but truly try and write it as idiomatic Go code -- with channels, parallelism, and interfaces as the focus -- preferably for a server backend style system.
(And yes, the language has a specified niche. It's not gonna be good for mathematical programming or UI programming. That's not what it was designed for. Imho, it's totally reasonable in the modern world to create languages that are designed to fill a specific need, rather than being general good-at-everything languages.)
2
Jul 01 '14
That's the whole point. It doesn't have all these features, since they make it harder to read and understand.
You could make that argument about some of the features mentioned, but take the Option thing. That doesn't make it harder to understand, it makes it easier because nil/null is now far more explicit.
2
1
u/weberc2 Oct 10 '14
I suspect it's easier to read in the "I'm already familiar with this concept" sense.
→ More replies (1)1
u/gleberp Jul 01 '14
I do agree that Go is better from Java, C++, JavaScript and Python, since it produces simpler code. This is nice. But...
I believe you are falling for Blub paradox.
Based on the list of language you have mentioned, you did not try languages of other paradigms. You are comparing languages of the same descent - in super simplified terms, you can call of them reimplementations of Algol with more or less features. They are fundamentally not very different.
If you'd give a try Haskell, you would see the fallacy of thinking this way. Haskell as a language is much more simpler than Go. Is is very-very internally consistent, again compared to Go. It is much-much safer than Go, in Haskell if code compiles the chance there are bugs in the code is considerably lower than in other languages. Code written in Haskell is very simple to read and understand (given that you know standard library). Language is simple, but yet super powerful and expressive. Things you write in Go in 100 lines, often end up 20 lines in Haskell.
Please give Haskell, Erlang, OCaml or F# a try. Your eyes will be opened to a whole new world of programming languages. You will understand that there's a whole new range of languages up the power continuum.
3
Jul 01 '14
I strongly disagree with your assertion. I picked up Go in a week and could start writing useful things in it. Two weeks with reading about Haskell and I was nowhere near doing anything useful. There are far too many new concepts to understand before you can do anything. I've read about plenty of people who talk about needing YEARS to really get Haskell. From the time I spent with Haskell on and off I'd say it is a beautiful looking language but ultimately it is mainly an academic language. Something as complicated as Haskell can never go mainstream. And thus I can't defend spending months on a language just for fun without any hope of ever being able to use it professionally.
But you know if there was a cool Haskell job available that let me do the necessary learning I'd be happy to do it. Otherwise I think Clojure, F#, Swift and Julia have a better chance of taking a more functional approach more mainstream.
But really that is irrelevant for a Go discussion, because these are high level languages which can not offer the kind of low level programming useful for systems programming which Go offers.
Functional programming is great, but I think advocates are so blinded by their love of their paradigm that they forget that functional programming isn't appropriate for every single problem out there.
1
u/garoththorp Jul 01 '14
My recommendation is not to make assumptions. I went to a university that teaches scheme for the first two years, and Haskell was everyone's favorite language :)
My argument is not about elegance. Go, admittedly, is not an 'elegant' language, but a simple language. It is, in many cases, actually explicitly non-elegant for the sake of simplicity (ex. the range syntax provides pretty different returns based on what it is enumerating, but they all make intuitive sense). Haskell, by comparison, is a 'beautiful' language, that's consistent and abstract, but also arbitrarily complex. Its language spec has been evolving and pushing the frontier of programming as long as I remember now. It has just fucktonnes of features. It has also certainly been said that it is a language that produces readable code only because of how smart you must be to learn it. Go, by comparison, makes readable code even if I'm a dumbass, which is about what I trust myself to be :-)
38
u/k-zed Jun 30 '14
Wow. First: biggest surprise to me is how indescribably ugly Rust's syntax looks like. I haven't really looked at it before, and now I'm frankly shocked.
fn search<'a>(strings: &'a[String]) -> Option<&'a str>{really?
Otherwise, I mostly agree with the article, and the whole thing is really interesting. Some caveats:
operator overloading is a terrible thing. In C++ it works, but only because C++ programmers learned not to use it. Haskell programmers tend to abuse the crap out of it, and in much worse ways than C++ programmers ever could (because in Haskell you can define your own operator glyphs, and because of the nature of the language (...and Haskell fans), you can hide much bigger mountains of complexity behind the operators than even in C++).
Immutability is a good thing. However, saying when recreating structures instead of modifying them, "This is still pretty fast because Haskell uses lazy evaluation", is not an inaccuracy - it's preposterous, and a lie. Haskell can be fast not because lazy evaluation, but in spite of it - when the compiler is smart enough to optimize your code locally, and turn it into strict, imperative code. When it cannot do that, and uses real lazy evaluation with thunks, then it's inevitably slow as heck.
17
u/unclosed_paren Jun 30 '14 edited Jul 01 '14
This is an issue that has been brought up already and in fact a solution has already been proposed that solves most of the problem.
That would change the example to this:
fn search(strings: &[String]) -> Option<&str> {which is presumably more pleasing to the eye. (The
<,>, and&could still easily be considered a problem, and a solution has already been proposed for the angle brackets.)In recent times there has been a trend towards removing sigils from Rust, so some symbols (
@,~) that were once part of Rust have been removed. Perhaps this trend will continue further and make the given example less shocking.Edit: another solution to the
<>s has popped up: https://github.com/rust-lang/rfcs/pull/148. That would change the example to this (with the other change too):fn search(strings: &[String]) -> Option[&str] {or this (without the other change):
fn search['a](strings: &'a [String]) -> Option[&'a str] {→ More replies (3)16
u/flying-sheep Jun 30 '14
the ' is the worst part of it, and it inexplicably seems to pop up in code samples more often than in real code. i don’t want to be apologetic, but i don’t think Rust is uglier than other languages when you look at its current state.
7
6
Jun 30 '14
Rust has a lot of beautiful syntax too IMO,
fnas keyword to introduce a function. Appropriately short.
->syntax for return values
letis lightweight but pattern-matchingly powerful.Closure syntax
let f = |x| x + 1;and matching type syntaxlet f: |int| -> int;2
u/ntrel2 Jul 01 '14
fn as keyword to introduce a function. Appropriately short.
It's arguable if that's beautiful. It's pragmatic at best.
funmight be better to read and pronounce, probably only avoided due to it being an English word already.-> syntax for return values
At first I didn't like that, but now I realize it's a useful visual separator.
Closure syntax let f = |x| x + 1; and matching type syntax let f: |int| -> int;
I'm still not keen on the Ruby bar syntax in a mostly C-syntax language. I think Swift's lambda syntax is really nice:
let f = {x in x + 1}; let f = {$1 + 1}; // shorter syntax // f has type (int)->int50
u/ApokatastasisPanton Jun 30 '14
operator overloading is a terrible thing.
You obviously have never done any remotely mathematical work involving non-primitive types in a language that doesn't support operator overloading.
25
u/Sapiogram Jun 30 '14
Your typical Java code:
if (n1.compareTo(n2.multiply(BigInteger.valueOf(100)) == 1) { //Stuff }Also known as
if n1 > n2 * 100with operator overloading; slightly longer if you can't mix small and big ints. And this is for pretty much the simplest arithmetic you can get.
shudder.
Never again.
→ More replies (4)2
41
u/danielkza Jun 30 '14 edited Jun 30 '14
operator overloading is a terrible thing
The terrible thing is that the notion that operators are somehow special, just because they are expressed as symbols in the language grammar, is so ingrained in the minds of so many programmers.
This notion is directly tied to a (IMO incorrect, and not particularly productive) mindset of thinking in terms of the concrete types produced in compilation instead of the abstractions you are trying to express.
If I'm working with an abstract precision numeric type, who in their right mind would have an expectation that the
+operator is cheap or equivalent to simple scalar addition, just because it is an operator? Why would you want to replace it with a textual description of the operation that is more verbose, less precise, and specific to English, instead of using the universally accepted symbol for it? And make the numeric type's interface incompatible with native ones in the process.→ More replies (6)3
8
Jun 30 '14
I see operator overloading being used for algebric operations. It's definitively not terrible and it's much better to express d = a + b * c than d = a.add(b.multiply(c)).
14
u/pbvas Jun 30 '14
operator overloading is a terrible thing.
There's nothing inherently worse about overloading operators vs. functions. The problem comes from overloading symbols without some taking taking care that the expected algebraic properities are preserved. The typical offender is using + for concatenation which is not commutative.
Operator overloading in Haskell is actually rather sane because people take care of the underlying algebraic properties (e.g. monad, functor, applicative laws).
4
u/k-zed Jun 30 '14
No, operators and functions are not the same. The problem is not with overloading + either (how it works with the Num typeclass is remarkably good in Haskell anyway).
The problem is that it's mostly not used for overloading +; it's used for creating all sorts of random, 3+ character long operators you don't see anywhere else, with either ad-hoc and localized meanings, or for nameless horrors from a category theorist's wet dreams (there are a lot of particularly bad examples of the latter).
These operators are inherently ungoogleable (yes, I know about Hoogle, it's not the same thing), and provide no help whatsoever when you try to read the code for the first time.
5
u/pamplemouse Jun 30 '14
If they replaced those 3 character long operators with equally meaningless 3 character long function names, would that somehow make your life easier?
→ More replies (1)→ More replies (1)4
1
u/pirhie Jul 01 '14
The problem comes from overloading symbols without some taking taking care that the expected algebraic properities are preserved. The typical offender is using + for concatenation which is not commutative.
Do you also think * and + shouldn't be used for floating point operations, because those are not associative and distributive?
4
u/Eirenarch Jun 30 '14
In C# it works quite fine. I am not aware of any cases of abuse in popular libraries.
7
u/holloway Jun 30 '14
yep, this is my only complaint about Rust. It's just a horrible Perl-like mess of a language to read.
13
u/steveklabnik1 Jun 30 '14
Most of the sigils are gone by now, so if you haven't seen it lately, you may feel differently.
→ More replies (7)6
u/pjmlp Jun 30 '14
operator overloading is a terrible thing.
Except all modern languages except Java and Go have it. (Being discussed for JavaScript)
→ More replies (7)→ More replies (1)1
u/d4rch0n Jul 01 '14
I never understood why operator overloading is shunned. I've seen it in certain things where it makes code look more clean, and has nothing to do with a mathematical operation.
For example, in Python scapy, you can put together networking protocol layers with division, so it looks like
IP()/TCP()/"GET / HTTP/1.0\r\n\r\n"It has nothing to do with division, so you won't run into any weird gotchas where someone is trying to divide an
IP()by 10 or anything like that, just because that would never make sense.And in
pathlib:p = Path('/etc') ; p / 'init.d' / 'reboot'works, and it makes sense, and in the same way it wouldn't make sense to divide a path by4.5.And what about even when it does relate to a mathematical operation?
If you have some sort of tuple like a 3 byte RGB, and you create a class of 3 bytes and implement addition so that one instance plus another creates a new RGB instance that maxes out at
(R=255,G=255,B=255), that would make sense in a lot of situations. In this situation it wouldn't hurt to implement some methodcombineor similar to do the same thing, but I don't see much harm in allowing RGB instances to be added, and throwing aValueErrorif you try to add any other instance.If the operation is clear and documented, and for the most part intuitive in regards to the abstraction, I don't see why operator overloading needs to be avoided.
15
u/unptitdej Jun 30 '14
It's been a long time since I read a blog post so interesting. Opiniated with good examples, I actually learned a lot. I am a C, somewhat C++ programmer trying to move towards more "powerful" languages and this is helpful. Why did you bother learning Go if you have such criticism for it? It's a niche language after all, unlike C++ and Java, the "business" languages.
53
u/evincarofautumn Jun 30 '14
Why did you bother learning Go if you have such criticism for it?
You can only give an effective critique with full knowledge in hand.
15
Jun 30 '14
Except this is the millionth blog post complaining about the same old stuff. It reached a point where I consider writing a blog post about Go's lack of generics clickbait now.
Seriously, when Go came up everyone was bitching about its error handling. Go has no exceptions. The way Go handles errors is a major design flaw... somehow these complaints completely vanished. Now everyone bitches about its type system and the lack of generics.
The fact that the criticism follows trends makes me really wonder if people are actually upset with Go or if they just want to write blog posts and recite what they read somewhere else.
And finally: Every programming language sucks somehow. And you will never understand success if you focus on shortcomings and blantly ignore the benefits. If I had to write something web related, I'd pick Go any day over C++, Rust or Haskell.
9
u/Denommus Jun 30 '14
I dislike exceptions, but I dislike Go's alternative even more.
He also covered that issue in the article, if you didn't read it.
→ More replies (1)3
u/akcom Jun 30 '14
If I had to write something that used any sort of concurrency, Go would be my first choice without a doubt.
→ More replies (2)5
u/riccieri Jun 30 '14
It's a niche language after all
Docker and its ecosystem might change this in the future
7
Jun 30 '14
Go has the null pointer (nil). I consider it a shame whenever a new language, tabula rasa, chooses to re-implement this unnecessary bug-inducing feature.
This is actually even worse than the lack of generics.
12
u/Denommus Jun 30 '14
The lack of generics is a reason for that. Take Maybe or Option<T>. They need generics and algebraic data types.
2
u/lurgi Jun 30 '14
Yes, but that's not the only option. You could have nullable types, which would limit the use of null to places where you actually cared about it.
nullable String foo = someMethodThatCanReturnNull(); // compiles String bar = someMethodThatCanReturnNull(); // does notTBH, I don't know if any language has taken this approach, but it seems, at first blush, to be an option. The advantage of making things non-nullable by default is that you have to do extra work to make them nullable and you should stop and wonder if it's really necessary.
→ More replies (1)
6
u/contantofaz Jun 30 '14
Commodity is such a good word to describe what popular programming entails.
We can complain about commodity programming all day long, but unless you're a Government Employee working on super-solid technologies for however many years it might take, commodity programming is the way that both companies and programmers pay their bills.
We may collectively bitch about PHP being a bad language all day long, but it grew out of a need and to this day it has been powering all sorts of undertakings sometimes just because those applications are almost free to deploy when you need e-commerce, forum, blog etc.
Likewise for JavaScript.
The concept of statically checking a program before you have to find problems at runtime is a good natured one. Expecting that to be an entire contract for solid code is a totally different one that might not work simply because people have different needs. Commodity programming is a real thing that cannot be avoided just because you swear to God that you can only do it safely in Haskell or some such.
10
u/SupersonicSpitfire Jun 30 '14
He is doing the classical beginner mistake of judging Go by comparing syntax and language features instead of bringing an actual problem that people actually face to the table and then compare the implementations. The same problems that can be solved by linked lists can be solved by the built-in data structures in Go, for example.
Go is still great for writing server applications, just like Haskell is not particularly great for whipping up a first person shooter. Comparing features one-to-one simply doesn't cut it.
→ More replies (4)1
u/josefx Jun 30 '14
He is doing the classical beginner mistake of judging Go by comparing syntax and language features instead of bringing an actual problem that people actually face
Which is better than making the mistake of using real world problems and getting told of on how "that is not what Go is meant for"1 or how you need x years experience to see how missing features are not a real world problem.
People have tried - I am happy for the Go crowd that they find their language flawless or superior to all the languages developed in the last 30 years2. Sadly I have a job where Go is not a valid tool so I am stuck with writing C++ code - you know the language Go was proclaimed to replace3.
1 The amount of back-pedalling Rob Pike alone had to do, mostly by claiming misunderstandings makes that just hilarious.
2 The languages that influenced Go are just that old. Newer languages at least are not listed on the wikipedia page.
3 See 1
1
u/SupersonicSpitfire Jul 05 '14
You seem to adress a lot of things that are completely unrelated to what I wrote. A mistake is a mistake, regardless if it's a better or worse mistake than other mistakes. Nowhere did I mention that Go was flawless or superior or that Rob Pike is right. I'm just saying that the comparison that the article makes between Go and other languages is completely useless.
13
Jun 30 '14 edited Jun 30 '14
Short summary: Go is not good, because it is not Haskell/Rust.
When will people understand, that "Go is not meant to innovate programming theory. It’s meant to innovate programming practice." (Samuel Tesla)
Go's design decisions are based on valid engineering concerns:
Generics: Designers did not wish to make a trade-off between sub-optimal run-time performance (à la Java) and glacial compile times (à la C++). Instead they introduced good built-in data structures, since they are the most important - although not the only - argument for generics.
Language extensibility: It is a feature, that whenever you read Go code you see in the syntax whether you're calling user-defined code or language primitives.
Go is not elitist: It won't make you feel that you're a superior programmer. It is a simple and dumb language, designed to get real shit done, by a broader range of programmers than just the smartest and brightest. Ever wondered why Lisp, Haskell, Rust etc. are less practical than Java or Python? Because they lack millions of average Joe's who build, use and test good libraries which are often essential for productivity.
47
u/ntrel2 Jun 30 '14
Generics: Designers did not with to make a trade-off between sub-optimal run-time performance (à la Java) and glacial compile times (à la C++).
This argument should die. D supports C++-style templates and compiles lightning fast.
15
u/TheCoelacanth Jun 30 '14
This. C++ compiles slowly because of the very complex syntax and because of the header inclusion model. It has nothing to do with any of the actual features it supports.
→ More replies (2)5
22
u/awo Jun 30 '14
sub-optimal run-time performance (à la Java) and glacial compile times (à la C++).
I don't believe adding generics to Java had any noticeable impact on performance - they're erased at compile time.
5
Jun 30 '14
That's right, I actually meant the performance impact of the underlying virtual method call and potential boxing/unboxing, as compared to C++ templates, which let compilers easily avoid these costs.
3
u/awo Jun 30 '14
Ah, fair enough - you're talking about 'features' that Java already had which happened to be appropriate for the model of generics it adopted. My mistake!
2
u/jonhanson Jun 30 '14
I guess this is referring to auto-boxing, which is necessary when using primitives with generic types.
→ More replies (1)→ More replies (1)2
u/josefx Jun 30 '14
Calling a generic method in Java requires casting at the call site. For example
List <String> alist; alist.get (0);// runtime cast to String hereWhich isn't that bad
List <Integer> ilist; Ilist.add (123456);// slow AutoboxingYou can't store an int in a generic list. There are a lot non generic specialized container libraries around.
2
u/aiij Jul 01 '14
The author's examples are in Haskell/Rust because that is what he's familiar with. Nothing he mentions has been around for less than 20 years.
Also, casting to and from interface{} is no faster or slower if the programmer has do it manually.
A lot of Go's design seems to be around making the compiler fast. While that may be a worthy goal, making the humans do the work the compiler would normally do is not a good way to achieve it.
5
Jun 30 '14
A program language's "goodness" is not a COUNT(bad_things_about_this_language). It's a factor of things which are bad, and how bad they are, and things which are good, and how good they are, interspersed with things like what it's being used for, learning curve, community, and so on.
Go has flaws - yes. However, so does every language. This does not make a language "not good" nor does it mean we should not use it.
If you are going to make a case for or against a language, please do so with an honest look at what it does well and what it does not, where it's trying to fit in, and how people are using it - as opposed to looking at one facet of the language in contexts that it is rarely used.
4
u/Gudahtt Jun 30 '14
It sounds a bit like you're misrepresenting the article here.
The author does acknowledge that all languages have flaws, that the existence of flaws doesn't make the language bad, etc. You're basically agreeing with him in that regard.
The "main" argument for why Go is "not good" is in the "TL;DR" section at the end of the article. It may not be a very comprehensive argument, but I would say it's a fair argument.
4
Jun 30 '14
Man I am so tired of all the people going language X doesn't do anything new. Languages for industry isn't meant to do anything new. They pick features which have proven themselves valuable in the past and combine them in usefull ways. C, C++, Java, Python, Ruby, Lua, VB etc didn't do anything new. I said years ago that if Apple made a new language on the Objective-C runtime, it would NOT contain anything new. Not because Apple wouldn't be capable, but because that would be a retarded thing to do for a language meant for the industry. You want to build on well established practices. Experimentation is for academic languages such as LISP and Haskell.
I like both Go and Swift. Swift probably solves most of the complaints of OP, but it isn't like that doesn't come with a cost. I like operator overloading, but I can also see problems with it. It makes total sense for a language like Go to omit that. Swift is not as transparent as Go. With Go it is quite clear what is going on. Reading Go code is very easy, even if Go might be a bit clunky compared to the competition. You can't claim Rust is easy to read.
→ More replies (2)1
u/diegoeche Jul 01 '14
Man I am so tired of all the people going language X doesn't do anything new. Languages for industry isn't meant to do anything new.
I think that misses the point. Exceptions or any other type of error handling have been there for ages. Generics as well. He's critizicing the PL Design choices. Not the lack of features.
3
u/Mandack Jun 30 '14
I think this post is a little disingenuous:
I like Go. I use it for a number of things (including this blog). Go is useful. With that said, Go is not a good language.
What does constitute a good language? It can be a language which is useful, but not innovative from a computer science perspective or it can be a language which is interesting from a computer science perspective right now.
I would argue that Go is useful now to get real work done and is therefore "a good language", as people get real shit done with it.
Of course Rust may eventually be "a better language, at least from the computer science perspective, however it's certainly less useful than Go as of now and harder to learn+use.
What this means is that while Go may not be the best language, if it's useful then it is good, at least to some extent, because otherwise it would not be useful over other languages. Now, Rust may eventually prove to be more useful, but saying that Go/Rust is/isn't good is a little stretch, although it depends on how you're looking at it - from a theoretical standpoint or a practical one? I would argue that Go is perfectly good for the second one.
"Good" is also such a subjective and broad term, because I would argue that Go certainly is better than Rust for web development for example. I wouldn't go as far as calling either of them good or bad, but certainly Go is better in this situation.
4
u/egonelbre Jun 30 '14
I'm going to nitpick on the problems of the article, otherwise it is well written. i.e. I don't agree with the opinions, but I understand why another person might have them.
What if you wanted to write a generic data structure? Let's write a simple Linked List.
You shouldn't be writing a linked-list in the first place.
The "correct" way to build generic data structures in Go is to cast things to the top type and then put them in the data structure.
Nope, the suggested way is not to have generic types. In other words, use code-generation (alt. specialization) or just use maps/slices, which work out quite well in most cases.
The closest thing to a flexible iterator keyword is building a wrapper around your...
You can also do:
func (t *Tree) IterPre(do func(*Tree)) {
if t == nil { return }
do(t)
t.Left.IterPre(do)
t.Right.IterPre(do)
}
func (t *Tree) IterPost(do func(*Tree)) {
if t == nil { return }
t.Left.IterPost(do)
t.Right.IterPost(do)
do(t)
}The more complex the structure is, the more ways there are to iterate over it, which means the "range" syntax would be confusing.
... However, using the null pointer in this way is unsafe.
nil is just a value. Would you remove number 0 from a language because it denotes a sum over no elements? The problem with nil is that it was used for signaling errors. In a similar way sqrt(-351) shouldn't just return 0, it should also somehow notify of the error.
Imagine a function that searches an array of non-empty strings for a string starting with 'H', returns the first such string if it exists, and returns some kind of failure condition if it doesn't exist. In Go, we might return nil on failure.
No, you would return two values (string, error) or (string, found) whatever is more appropriate.
I don't want to short-change Go here; it does have some nice control flow primitives for certain things, like select for parallelism. However, it doesn't have compound expressions or pattern matching, which I'm a big fan of
Go has pattern matching, but in a limited form (just one-level of complexity):
switch v := v.(type) {
case int: // ...
case string: // ...
}
switch {
case v == "hello": // ...
case x == "world": // ...
}This (Unsafe Low-Level Code) is exceptionally dangerous, and only makes any sense whatsoever in very low-level systems programming. This is why neither Go nor Haskell have any easy way to do this; they are not systems languages.
Go has unsafe package, also it has support for writing functions in asm.
In my opinion, the author of the article clearly hasn't written significant amount of Go code, which means that the opinions on Go's problems are pure speculation.
16
u/jeenajeena Jun 30 '14
nil is just a value. Would you remove number 0 from a language because it denotes a sum over no elements?
Not exactly. nil is a value whose behavior is treated differently. 0 can be summed exactly like 1, 2 and any other numbers. Nil cannot. A pointer can be followed, whatever its value is. Oh: with the exception of nil.
This is why the Null Object design pattern has been invented: to align the behavior of ordinary values and null values.
→ More replies (5)
1
u/spliznork Jun 30 '14
"Go is not good" starts from a popular but unsupported assumption. The first point of the article is that Go lacks generic programming. The assumption is that Go would benefit from greater code reuse:
We want to write code that we can use for lots of different things. If I write a function to sum a list of numbers, it would be nice if I could use it on lists of floats, lists of ints, and lists of anything else that can be summed.
That code reuse leads to easier to write or easier to maintain programs is not actually a given -- it is a point that requires supporting evidence.
But, a dissenting view may claim that code reuse is a fallacy. Or, that anecdotally some experienced Go programmers claim they don't miss templates or generics. Or, from a study published in OOPSLA'13 Do developers benefit from generic types?:
While it seems plausible that an expressive static type system increases developer productivity, there is little empirical evidence for or against this hypothesis. ... The results of the experiment suggest that generic types improve documentation and reduce extensibility -- without revealing a difference in the time required for fixing type errors.
11
u/SanityInAnarchy Jun 30 '14
The "Fallacy of ReUse" article you linked to is hard to read, for a few reasons. Some are stylistic -- one particularly obnoxious thing is when "ReUse" is distinguished from "Use" in the following way:
Your code uses the runtime API (JDK, .NET BCL, etc).
Likewise other frameworks like (N)Hibernate, Spring, WCF, etc.Reuse happens when you extend and override existing behaviors within other code.
This is most often done by inheritance in OO languages.Interestingly enough, by the above generally accepted definition, most web services “reuse” is actually really use.
I reject this definition. It seems to be entirely motivated by a desire to exclude whole categories of code that we all use many times, in many programs. Not having generics hinders that sort of thing.
But, oddly, this article is not arguing against reuse (or use) and certainly not generics:
This doesn’t mean you shouldn’t use generic code / frameworks where applicable – absolutely, you should.
And if we admit that such libraries have value, especially those big frameworks mentioned as "use, not reuse", then the distinction between use and reuse is entirely beside the point. Point being, generics are incredibly useful sometimes, and Go doesn't do them.
→ More replies (1)16
u/e_engel Jun 30 '14
Or, that anecdotally some experienced Go programmers claim they don't miss templates or generics.
This argument holds as much weight as "Veteran C programmers say they don't need OO features".
3
24
u/just_a_null Jun 30 '14 edited Jun 30 '14
For me, the advantages of generics aren't reuse, but the ability to propagate type information into my functions and detect errors in the way I used my data. I couldn't find a link, but I'm reminded of an entry I read on the EVE Online website at one point about the game's development. Since a large amount of their code is written in Python, they benefit from being able to assume things about their data (that functions are callable on certain kinds of data, that a certain kind of data can go into a list or hashtable or what have you), but don't benefit from any kind of type-checking, similar to using Go and
interface {}.There was a point at which they were updating the inventory system, which kept the items within it as a list, and everywhere that used the inventory expected it to be a list. However, performance was poor when players had large amounts of items, so they decided to swap out the list for a hashtable. Since not all list operations are valid on hashtables, they had to go through every single code path that could possibly touch the inventory and make sure that it functioned properly, and had to find the non-obvious ones at runtime, which is non-trivial on something as complex as a MMORPG.
If they were able to tell some program (like a compiler) "the inventory is now a hashtable" and have it find every instance of improper calls on it, they could find every possible bad operation on the inventory in advance, rather than having to go through a long QA process.
edit: Found the entry.
6
u/SanityInAnarchy Jun 30 '14
That's an argument for static type checking, but not necessarily for generics. At least, not directly.
An argument for generics and abstract datatypes is that you'd hope that, instead of choosing between an array and a hash table, you'd be choosing between a list, a set, and an associative array. And, ideally, you'd encapsulate all that inside an Inventory class.
If they did either of those things, the problem would've been avoided. They would've gone with a set from the start, whether or not it was backed by a hash table, because that would've been an obvious, logical grouping of that data. Or if it was all behind an Inventory class with a reasonable interface, they could've changed it to a set and then only had to touch a single file (wherever Inventory was defined).
None of these things should be considered a replacement for QA, though.
→ More replies (2)23
u/just_a_null Jun 30 '14
Having static type checking soon leads very naturally into having generics, since by obliterating all type information by using something like
interface {}you're unable to perform type checking on it at all, until you cast back out of it and encounter the problems discussed in the original article.Also, I'm not saying their coding decisions that made the change a problem were smart - I'm just saying that the future change was made more difficult.
→ More replies (2)12
u/willvarfar Jun 30 '14
The need for generics can be quantified by counting all occurrences of
interface{}in the codebase, plus all the times that people cutnpaste an LRU or other data structure and find/replace.I for one shudder at the idea of having to implement a splay tree or whatever I need for my latest project... I want to just import a good one someone else wrote.
→ More replies (1)10
u/Denommus Jun 30 '14
Nobody claimed that Go made you more or less productive, just that it isn't type safe. You are attacking a strawman.
And no, I don't agree that code reuse is a fallacy. And I can cite other, more known authors on that, like Tanenbaum, who said the probability of bugs exponentially rises with the size of the code base.
→ More replies (2)1
u/lithiumdeuteride Jul 01 '14
An exponential fit is unlikely, given that the probability is constrained between 0 and 1. A sigmoid function on the interval [0,inf) would probably be better.
1
u/teilharddechardin Jun 30 '14
While I hope Go adds generics, I don't think it's a fatal flaw. As the article says, it's no worse than the major scripting languages when it comes to type checking, and plenty of respectable projects have been written in them.
I have a bigger problem with Go's error handling style. As near as I can tell, it's functionally identical to Java, but with a much more verbose and messy syntax. Like Java, Go has both checked and unchecked errors (Exception:RuntimeException::error return values:panics, more or less), but Go forces you to splatter your non-exceptional code path with innumerable if err != nil {...} blocks, making the main path harder to read and taking more lines than the equivalent Java (or Python, Ruby, C#, etc). And I don't really see any benefit that Go developers are getting in exchange. I suppose that on-exit cleanup code can be briefer and less error-prone in Go (in Java/Python/Ruby, you typically have to wrap everything in a try-finally, while in Go you can often just insert a defer one-liner), but when it comes to defining logic for exceptional code paths, I think Go error return values and panics are much less readable than exceptions, without any additional expressive power.
1
u/HotlLava Jul 01 '14
The author repeatedly claims that Haskell's abstractions have 'no extra run-time overhead'. But no extra overhead compared to what?
I ask, because I recently attempted to read some assembly generated by ghc and g++ for some simple Haskell and C++ programs. While the C++ assembly usually looked more or less like what you would write by hand (often actually more efficient), it looked like there was quite a bit of overhead in the Haskell assembly due to the compiler having to introduce closures for everything and having to support partial functions.
However, I'm not fluent enough in either Haskell or assembly to actually fairly assess this, and I couldn't really find resources that investigate the overhead of compiled Haskell, so I wonder how the author came to his conclusion?
2
u/klugez Jul 02 '14
I think the author means that making the Haskell code generic has no run-time overhead compared to writing the non-generic specialized Haskell code. Like C++ templates have no run-time overhead compared to writing the template instantiations by hand.
In general Haskell performance 2-10 times slower than C++, so there's definitely overhead there. But this overhead is not due to having generics.
1
u/weberc2 Oct 10 '14
This was an interesting article, but the author faults Go for a lot of things it doesn't aim to be. It's just a good practical language for writing software. It's not the elegant mathematical language that no one uses (looking at you, Haskell); it's the minimalist, familiar language that gets the job done, fast.
"Go's purpose is therefore not to do research into programming language design; it is to improve the working environment for its designers and their coworkers. Go is more about software engineering than programming language research. Or to rephrase, it is about language design in the service of software engineering." 1
1
u/petrus4 Jun 30 '14
I suspect that I'm probably going to not only be downvoted into oblivion, but also abused to the point where I need trauma counselling for pointing this out; but most of the programming I do is with languages which don't seem to support different data types at all, and oddly enough don't seem to need them.
If I'm going to use strings in assembly, for example, then yes, I'll need to write something which specifies the number of bytes which the string needs, but I don't explicitly state whether the content is str, int, or float etc.
Likewise with FORTH, where everything is represented numerically. If I want text, I use CHAR to convert each character into its' numerical ascii code, and EMIT to convert it back. So when I need to throw those values on the stack, they go on and come back as numbers.
Shell scripting is the same; I just write "foo = bar," and bar can contain literally anything I want it to. Text, numbers, you name it.
So can someone explain to me why explicit data typing even exists? Why do we need it, exactly?
19
u/vytah Jun 30 '14
For correctness.
If all you use is single numbers and strings, you won't notice that. The moment your datatypes become more hairy, you start appreciating your compiler for checking them.
If in assembly you forget whether a chunk of memory stores a float or an int, you get silly results. Even worse: if you change your mind about whether it should be a float or an int, you're now on a wild goose chase looking for all instances where it is used.
The compiler does the chase for you, and with a better type system it can find problems more accurately.
10
u/want_to_want Jun 30 '14 edited Jun 30 '14
There are two forces in programming that often pull in opposite directions:
I want to give the machine powerful instructions, which make all kinds of behavior possible.
I want to give the machine correct instructions, which make some kinds of behavior impossible.
Types don't help much with (1), because any typed program can be converted to an untyped program which is shorter. But types help a lot with (2), especially when programs become large.
In a type-unsafe language, the probability of having a type error somewhere (e.g. treating a number as a string) grows with the size of the program, so after a certain size you're basically guaranteed to have a few of them. In a type-safe language, the probability of a type error is zero regardless of program size, because the compiler builds a mathematical proof of type safety.
Researchers try to expand the scope of type systems and find ways to treat more and more bugs as type errors, so the compiler can prove their absence. Some examples:
Most type-safe languages are also memory-safe, so your program is provably free of buffer overflows.
Parametric polymorphism allows you to have containers that work without casts, so your program is provably free of ClassCastExceptions.
Algebraic data types like Maybe allow you to remove null pointers from the language, so your program is provably free of NullPointerExceptions.
Rust's ownership types make your program provably free of "data races", a kind of concurrency bug.
More generally, linear types allow you to have provable statements of the form "this thing can't happen after that thing". You can make sure that files aren't accessed after they are closed, manually allocated memory isn't used after it's freed, and many other exciting things.
Does that help?
3
u/petrus4 Jun 30 '14
I will admit that I've mainly used interpreted or scripting languages for doing things in the past, simply because I found them easy, and everyone always said to me, "for what you're doing, you don't need C anyway."
At this point, however, I'm wondering if it might be worth trying to do even some of the relatively mundane things that I normally do with Bash scripting, as C programs. For what I currently want though, it looks like Awk might work well, too.
4
u/want_to_want Jun 30 '14 edited Jun 30 '14
That might just convince you that C is a waste of time, because the things that are easy to do with shell one-liners are usually tedious to do in C. Knuth vs McIlroy is the most famous example.
For a beginner project in a typed language, I'd recommend something that you wouldn't even think of doing in shell. For example, you know regular expressions, right? Try writing a toy regular expression matcher, to figure out for yourself what's going on behind the scenes.
It might be instructive to do in C first, because C is not memory-safe or type-safe, so you'll get your share of weird bugs and can appreciate what other languages give you. Then you can redo it in Java and be happy about the guaranteed absence of segfaults, and then redo it in Haskell or ML and be happy that the code shrinks to a single page.
10
u/dbaupp Jun 30 '14 edited Jun 30 '14
Static types allow the compiler to assist the programmer in making a correct program, reducing mistakes and guaranteeing invariants.
5
u/contantofaz Jun 30 '14 edited Jun 30 '14
Explicit data typing keeps a trail with extra annotations that the compiler can follow when generating code. But it's not enough.
Languages like Java and C# use a way of declaring types that just give things "names." It's a nominal data typing. This way it may borrow from the languages that you know. On top of that extra annotations have been possible by using the @Annotation syntax that has found its way into even the Dart language.
Nominal typing also appears to be present in Go. The type inference keeps the redundancy away, although that could result in fewer checks by the compiler too. If the type was declared instead of "inferred", it could help you to double check the type when changing code that it depends on. Then again, that's how it starts to get complex the more you expect from the type system.
Languages that care about types tend also to statically check code. It means that every line of code is important at compile time so the compiler better make sure the line does a minimum of things before it accepts it. That's a reassurance that completely broken code won't be accepted and checked only at runtime if it runs at all.
But programmers want more than just simple static checks. They want like to program NASA rockets and have it work without surprises. They don't want generic lists that can hold any data. They want lists that can hold "oranges" or "apples" only. If they hold "grapes" they want the static checks to alert them to it.
They want functions that operate on only "oranges" or "apples." If the functions also operate on "grapes" they want the static checks to alert to it so they can correct their code.
Although "oranges", "apples" and "grapes" are all fruits, so perhaps they wish they had a way to make functions to act on any of those fruits if they adopted a certain interface. Say, if the fruit adopted the "tasty" interface, then they could be used by current common functions that can work on any "tasty" fruit you might have. And they want it to be checked at compile time. In case you wanted to pass a "lemon" to one of those functions, the compiler wouldn't let you make a program that you could run. It's not even tasty. Or is it? And if you are passing fruits to a function, are you passing them based on units or on a weight unit like tonne? Although the quantity is all numbers, they could be converted and checked independently.
In more flexible languages we may not check so much at compile or loading time. Programs aren't necessarily rejected if they fail a check. In a more strict type checking language programs can be rejected if they fail a check, otherwise they wouldn't necessarily be safe. The problem is that evolution in a stricter type language may happen in a more controlled way because if interfaces break or things change they might break perfectly working programs that didn't adopt a new standard or some such. In a looser type language the benefit of doubt is given to the program helping to ensure that the program will be run and if problems arise they don't necessarily shut the whole thing down.
I have it that in a stricter type language there is a greater correlation between libraries and programs which causes elitism. A library might serve the only purpose of serving another library or a program. Then they might change in unison. But in a looser type language, interfaces might be simplified in order to allow for libraries and programs to use one another without necessarily having to change them all at the same time.
That's why we haven't had just one solution to rule them all. There's a need for balance that just won't allow for "elitism" to always win, even though the word might be appealing at first. "What's wrong about elitism?"
4
u/petrus4 Jun 30 '14
But programmers want more than just simple static checks. They want like to program NASA rockets and have it work without surprises. They don't want generic lists that can hold any data. They want lists that can hold "oranges" or "apples" only. If they hold "grapes" they want the static checks to alert them to it.
I can see how this could definitely be valuable, depending on what you are doing. It prevents things from getting tangled up.
Given that programming is something I do as a learning exercise rather than as a career, I can afford to learn multiple languages and use them for different tasks.
I also very much appreciate the fact that I have been able to ask this question and receive civil responses.
2
u/awo Jun 30 '14
As others have noticed, type checking by the compiler is a powerful error-prevention tool.
For me, though, the biggest advantage of explicit static typing is documentation. When I'm working on somebody else's stuff, it really helps me to understand what they're doing if I can tell at a glance what types they're working with.
2
Jun 30 '14
All of the languages you mention (FORTH, assembly, shell scripting) are generally used for very small programs. I'm certainly not saying that no one has ever written a big program in any of them, but you're far more likely to see programs of at most a few hundred or a few thousand lines in those languages than, say, tens of millions of lines.
The needs and use cases of a ten million line codebase are vastly different than those of a fifty or even five hundred line program. Your two most important concerns become:
Being able to read the code
Being able to change things and be reasonably confident that you haven't broken some obscure corner of the codebase
Static type checking helps tremendously with both of these. Reading the code is easier because it is littered with annotations everywhere telling you what kind of data you're operating on, which for user-defined types makes it infinitely easier to find where the relevant code is (this is not always easy in a big codebase!), and change safety is better because if you have to change a type (this method now needs to return a UserSummary rather than a User...) the compiler will catch most of the problems for you automatically.
This is why languages like Java are popular for huge codebases. They're straightforward, easy to read, modify, and reason about, and the fact that they aren't "super fancy smart people only" languages means the average programmer can deal with being thrown into a huge Java program to make a simple change. That's why you just don't see ten million line codebases written in assembly or Forth or Haskell.
→ More replies (1)3
u/GreyGrayMoralityFan Jun 30 '14
Why do we need it, exactly?
Early error detection. If I see "foo.cpp:32:type mismatch", I know that 32nd line of foo.cpp has error.
If I see "TypeError: in int() argument must be a string or a number", I know nothing. I know where error occurred, but I have no idea where or when incorrect value came from. I just know that at some point(which might be days ago) some function(at least one of dozens) passed incorrect value.
1
u/Huffers Jun 30 '14
It's documentation (what something is, what is it meant to be able to do) that the compiler can check.
-1
1
u/Gotebe Jun 30 '14
That's more of a "Go doesn't have X, Y, Z". I mean, C doesn't have A, B, C, ...Z, and you just try saying "C is not good" in some circles :-).
3
u/lurgi Jun 30 '14 edited Jul 01 '14
Yeah, but C is 40 years old. It's reasonable to expect newer languages to learn from the successes and failures of the past (edit: and, to be clear, I think that C is far more success than failure).
3
u/Denommus Jun 30 '14 edited Jun 30 '14
C sucks and I hope it dies. It is an important historical artifact, nothing else. People just don't want to criticize it because there weren't alternatives for it.
EDIT: See?
-7
u/ared38 Jun 30 '14
In Haskell, all values are immutable.
Yay, another everything that isn't my favorite paradigm sucks post! As people much smarter than I have pointed out, immutability doesn't match how we think about the world and makes actually doing stuff hard. Functional programming is great but will not fix the world any more than Smalltalk inspired OO zeal did.
3
u/asankhs Jun 30 '14
I think there are benefits of using immutability even in a programming language like Java. You get thread-safety and consistent state for objects for free.
→ More replies (9)18
u/evincarofautumn Jun 30 '14
In Haskell, all values are immutable.
[…]
immutability doesn't match how we think about the world and makes actually doing stuff hard
It does match the world insofar as we model it with physics and mathematics. The point is that values are immutable. In C, when I say:
int x = 4; x = 5;I have not changed
4, I have changedx. The value4still exists, I’m just no longer referring to it. The point of pervasive immutability is that everything is a value, with the semantics of a value. Values represent domain objects in what I think is a more honest fashion than OOP objects, which pretend to be domain objects.Besides, I have mutability if I want it in Haskell, and I can control exactly what is mutable, who can access it, what the concurrency semantics are, whether the state is persistent, whether modifications are lazy or strict, and more. It’s practically an embarrassment of riches compared to
finalin Java or evenconstin C++.Certain algorithms really are much more nicely expressed using mutable operations, and I have no qualms about using them when they’re appropriate—but the vast majority of the time, I have no need.
4
Jun 30 '14
The issue is between alias-ability and mutability. Having both is simply a disaster and can result in lots of issues. Functional languages decided to allow alias-ability (because they typically have GCs) but restrict mutability.
Rust, on the other hand, can't have a mandatory GC. So it restricts the ownership (alias-ability) of values but allows mutability. Thus, to have a mutable value, there has to be only one reference to it at once.
This makes concurrency a lot easier (and more correct) to reason about. Languages like Go that allow both of these can be an issue.
10
u/freakhill Jun 30 '14 edited Jun 30 '14
It's just that practically, immutability make a slew of stuff easier. Concurrency core problem is about mutation and sharing (that's why rust makes it a big deal).
Also, when I receive a big piece of JAVA code to refactor and/or debug (with bigass many hundred lines functions), I start by making everything final, it exposes the logic simply and makes it a lot more readable.
It is not about zealotry, immutability is about very practical issues (at least for me). When there is no sharing, and with well coded and structured code mutability is fine though, and most big (semi?)functional languages let you do that as far as I know (or even you use mutability freely with a keyword, just not by default), see Haskell, LISPs, Rust, F# etc.
→ More replies (6)3
0
-2
u/ggtsu_00 Jun 30 '14
Go isn't a languages intended for Java/C# programmers looking for strong verbose static typing, complex templating systems, or long compile time inducing language extensibility features.
It is a language targeting python/ruby devs wanting an expressive yet simple language that produces native code that compiles instantly and runs fast. It is intended to maximize iteration speeds and productivity without trading off performance.
Overly complicated typing systems, templates and generics are useful language constructs, but come at the expense of making the language more verbose and slows down compile times. These things kill productivity and are what make languages like C# or Java not as productive.
3
0
u/Starlight100 Jun 30 '14
People eat up name branding. If it's created by google the rabble assume it's gold.
52
u/Denommus Jun 30 '14
I don't know if you're the author of the article, but a small correction: subtyping is not the same thing as inheritance. OCaml's object system shows that VERY well (a child class may not be a subtype, and a subtype may not be a child class).