News for hackers. Stuff that matters.
Re:The Next Step for Generics by gokhan on Tuesday June 16, 2020 @04:13PM (#23543497)
What's wrong with this?

  class Result<T>
  {
    bool IsSuccess {get; set;}
    string Message {get; set;}
    T Data {get; set;}
  }
On many occasions, I like using result types for defining a standard response for calls. It's typed and success / fail can be handled as a cross-cutting concern.
Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @04:18PM (#23543564)
That's a generic container of 0 or 1 elements ;)

It's also incredibly unsafe and why generics aren't enough. C++, Java, and so on have had generics for ages and with types like the one above, null pointer exceptions are incredibly common. Nothing prevents the user from attempting to retrieve the data without first retrieving the success status.

On the other hand, this improves on it dramatically:

    enum Result<T, E> {
      Success(T),
      Failure(E)
    }
Re:The Next Step for Generics by nicoburns on Tuesday June 16, 2020 @07:24PM (#23545574)
I'm convinced that lack of Sum Types like this in languages like Java/C#/Go are one of the key reasons that people prefer dynamic languages. It's incredibly freeing to be able to express "or". I do it all the time in JavaScript (variables in dynamic languages are basically one giant enum of every possible value), and I feel incredibly restricted when using a language that requires a class hierarchy to express this basic concept.
Re:The Next Step for Generics by fgonzag on Tuesday June 16, 2020 @08:07PM (#23545967)
I completely agree. Every passing day I become more convinced that a statically typed language without sum types or more broadly ADTs is fundamentally incomplete.

The good news is that many languages seem to be cozying up to them, and both the JVM (through Kotlin, Scala, et all) and .net (through F# or C# w/ language-ext) support them.

Even better news is that the C# team has stated that they want to implement Sum Types and ADTs into the language, and are actively looking into it.

Re:The Next Step for Generics by wvenable on Tuesday June 16, 2020 @10:27PM (#23547046)
I just don't see, in properly designed code, that there would be that much use for sum types if you have generics. When are you creating functions take or return radically different types that need to be expressed this way?

I dislike dynamic languages where parameters and variables can take on any type -- it's rarely the case that same variable/parameter would ever need to contain a string, a number, or a Widget in the same block of code.

I find it much more freeing to have the compiler be in charge of exactness so I can make whatever changes I need knowing that entire classes of mistakes are now impossible.

Re:The Next Step for Generics by frenchy on Tuesday June 16, 2020 @11:18PM (#23547364)
> When are you creating functions take or return radically different types that need to be expressed this way

Let's say you're opening a file that you think is a CSV. There can be several outcomes:

- the file doesn't exist

- the file can't be read

- the file can be read but isn't a valid CSV

- the file can be read and is valid, and you get some data

All of these are different types of results. You can get away with treating the first 3 as the same, but not the last. Without a tagged union, you'll probably resort to one of a few tricks:

- You'll have some sort of type with an error code, and a nullable data field. In reality, this is a tagged union, it's just that your compiler doesn't know about it and can't catch your errors.

- you'll return an error value and have some sort of "out" value with the data: this is basically the same as the previous example.

- you'll throw exceptions, which usually ends up with people writing code that forgets about the exception because the compiler doesn't care about it, and the code works 99% of the time until it completely blows up.

Re:The Next Step for Generics by rsanek on Wednesday June 17, 2020 @01:21AM (#23548095)
If you want to force people to handle the above 3 cases, couldn't you just throw separate checked exceptions (eg in Java)? In that case the compiler does care about it. You can still catch and ignore but that imo is not a limitation of the language's expressiveness.
Re:The Next Step for Generics by cmrdporcupine on Wednesday June 17, 2020 @09:34AM (#23551170)
Checked exceptions would have been an ok idea if it weren't for the fact that at least when I was writing Java last (almost 10 years ago) they were expressly discouraged in most code bases. Partially because people just get in the lazy habit of catch and rethrow RuntimeException, or catch and log, etc. when confronted with them. Partially because the JDK itself abused them in the early days for things people had no hope of handling properly.

They also tend to defer handling out into places where the context isn't always there.

The trend in language design does seem to be more broadly away from exceptions for this kind of thing and into generic pattern matching and status result types.

Re:The Next Step for Generics by mrkeen on Wednesday June 17, 2020 @11:43AM (#23552745)
> Checked exceptions would have been an ok idea

> Partially because people just get in the lazy habit of catch and rethrow RuntimeException, or catch and log, etc. when confronted with them.

After quite a while of thinking this way, I came to the conclusion that:

95% of the time, there's no way to 'handle' an error in a 'make it right' sense. Disk write failed? REST request failed? DNS lookup? There usually isn't an alternative to logging/rethrowing.

When there is a way to handle an error (usually by retrying?), it's top level anyway.

Furthermore, IO is the stuff that can just 'go wrong' regardless of how good the programmer is, and IO tends to sit at the bottom in most Java programs. This means every method call is prone to IOExceptions.

Re:The Next Step for Generics by cmrdporcupine on Wednesday June 17, 2020 @01:24PM (#23554052)
Yes, after a few years of Java we all end up there. Frankly it's a good argument for the Erlang "Let It Crash" philosophy.

https://verraes.net/2014/12/erlang-let-it-crash/

If IOException on a read is truly happening, and it isn't just a case of a missing file, there are serious issues that aren't going to be fixed with a catch-and-log, or be able to be handled further up the call stack.

Re:The Next Step for Generics by nicoburns on Wednesday June 17, 2020 @04:23PM (#23556272)
One benefit I've found with error-enums is just being aware of all the possible errors that can occur. You're right: 95% of the time you can't do anything except log/retry. But that 5% of the time become runtime bugs which are a massive pain. It's really nice when that is automatically surfaced for you at development time.
Re:The Next Step for Generics by frenchy on Wednesday June 17, 2020 @11:07AM (#23552323)
Note that checked exceptions are essentially the same thing as returning a tagged union, from a theoretical perspective at least.

They're not popular in Java though, because the ergonomics is a lot worse than working with a Result type.

Re:The Next Step for Generics by Mirioron on Wednesday June 17, 2020 @12:57AM (#23547969)
Honest question: do you think this kind of stuff is going to be adopted by the majority in the next decade or two? Because I'm looking at it and adding even more language features like that seems to make it even harder to read someone else's code.
Re:The Next Step for Generics by wokwokwok on Wednesday June 17, 2020 @02:19AM (#23548361)
um... you realize the parent post is talking about having sum types in statically typed languages (eg. rust), when you already do this all the time in dynamic languages like javascript and python right?

So, I mean, forget 'the next decade or two'; the majority of people are doing this right now; python and js are the probably the two most popular languages in use right now.

Will it end up in all statically typed languages? Dunno; I guess probably not in java or C# any time soon, but swift and kotlin support them already).

...ie. if your excuse for not wanting to learn it is that it's probably an edge case that most people don't have to care about now, and probably never will, you're mistaken I'm afraid.

It's a style of code that is very much currently in use.

Re:The Next Step for Generics by Mirioron on Wednesday June 17, 2020 @03:31PM (#23555684)
Are the majority actually writing code like this though? In the case of dynamic languages, this property seems more like an additional consequence of how the language behaves. It's not additional syntax.
Re:The Next Step for Generics by wokwokwok on Wednesday June 17, 2020 @09:26PM (#23558822)
> Are the majority actually writing code like this though?

Yes.

For example, some use cases: https://www.typescriptlang.org/v2/docs/handbook/unions-and-i...

This sort of code is very common.

I really don't know what more to say about this; if you don't want to use them, don't. ...but if your excuse for not using them is that other people don't, it's wrong.

Re:The Next Step for Generics by GolDDranks on Tuesday June 16, 2020 @10:49PM (#23547177)
Because even with generics, you are not able to express "or"; two different choices of types that have _different_ APIs. With generics, you can express n different choices of types that have all the _same_ API.

It's a good software engineering principle to make control and data flow as streamlined as possible, for similar data. Minimize branches and special cases. Generics help with this, they hide the "irrelevant" differences, surfacing only the relevant.

On the other hand, if there are _actually_ different cases, that need to be handled differently, you want to branch and you want to express that there are multiple choices. Sum types make this a compiler-checked type system feature.

Re:The Next Step for Generics by coolreader18 on Tuesday June 16, 2020 @10:51PM (#23547192)
Let's take Rust's hash map entry api[0], for example. How would you represent the return type of `.entry()` using only a class hierarchy?

    let v = match map.entry(key) {
        Entry::Occupied(o) => {
            o.get_mut() += 1;
            o.into_mut()
        }
        Entry::Vacant(v) => {
            update_vacant_count(v.key());
            v.insert(0)
        }
    };
I view sum types as enabling the exact same exactness as you describe in your last line; especially since you can easily switch/match based on a specific subtype if you realize you need that, without adding another method to the base class and copying into the x subclasses that you have for implementing the different behavior.

[0]: https://doc.rust-lang.org/std/collections/hash_map/enum.Entr...

Re:The Next Step for Generics by Ar-Curunir on Tuesday June 16, 2020 @10:43PM (#23547143)
Rust has both generics and sun types, and benefits enormously from both.

And sum types aren’t for “radically different types”. You can define an error type to be one of different options (I.e. a more principled error code), or to represent nullability in the type system, or to indicate fallibility without relying on exceptions, etc.

Rust uses all of these to great effect, and does so because these sum types are generic.

Re:The Next Step for Generics by dragonwriter on Tuesday June 16, 2020 @07:35PM (#23545689)
> I'm convinced that lack of Sum Types like this in languages like Java/C#/Go are one of the key reasons that people prefer dynamic languages.

It doesn't hurt that static languages (TypeScript) or tools (mypy) that lightly lay on top of dynamic languages often do support sum types.

Re:The Next Step for Generics by jcelerier on Tuesday June 16, 2020 @04:25PM (#23543630)
> It's also incredibly unsafe and why generics aren't enough. C++, Java, and so on have had generics for ages and with types like the one above, null pointer exceptions are incredibly common.

uh, you'd never get a null-pointer exception in C++ given the type that OP mentioned. Value types in C++ cannot be null (and most things are value types by a large margin).

Re:The Next Step for Generics by temac on Tuesday June 16, 2020 @05:21PM (#23544323)
> Value types in C++ cannot be null

They can just not exist. And C++ being C++, dereferencing an empty std::optional is UB. In practice this particular UB often leads to way worse consequences than more "conventional" null-pointer derefs.

Re:The Next Step for Generics by gpderetta on Tuesday June 16, 2020 @07:29PM (#23545620)
Then write your own optional that always checks on dereference or toggle whatever compilation flag enables checking in the standard library you are using.
Re:The Next Step for Generics by loopz on Tuesday June 16, 2020 @04:38PM (#23543782)
Instead you can have undefined behaviour in C++.

Don't think get;set is C++, though it breaks encapsulation.

Re:The Next Step for Generics by sedatk on Tuesday June 16, 2020 @04:38PM (#23543774)
You can also constrain a generic type only to value types in C#:

  class Result<T> where T: struct
  {
  ...
  }
In that case it can't be null with C# either.
Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @04:43PM (#23543839)
Then you can't construct it unless it's successful, no?

A Result<T> that can only contain successful values doesn't seem very useful

Re:The Next Step for Generics by sedatk on Tuesday June 16, 2020 @07:09PM (#23545458)
You can, it's possible to address "missing values" with a default construct. Example:

  int x = default; // x becomes zero
  T x = default; // x becomes whatever the default value for struct is
Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @07:25PM (#23545587)
Then we're back to accessing that value being an enormous footgun, yes?
Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @04:42PM (#23543831)
Then you can't construct it unless it's successful, no?

A Result<T> that can only contain successful values doesn't seem very useful

Re:The Next Step for Generics by joshuamorton on Tuesday June 16, 2020 @04:59PM (#23544037)
No, you just are forced to use methods like foo.UnwrapOr(default_value) to get the Result. Or depending on the language, you get a compile error if you don't handle both possible values of the Result enum in a switch statement or if/else clause.

See for example https://doc.rust-lang.org/std/result/enum.Result.html#method... in rust, https://docs.oracle.com/javase/8/docs/api/java/util/Optional... in Java, and https://en.cppreference.com/w/cpp/utility/optional/value_or in C++.

Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @05:16PM (#23544259)
Who are you replying to? Is any of your elaboration related to this result type?

    class Result<T>
    {
      bool IsSuccess {get; set;}
      string Message {get; set;}
      T Data {get; set;}
    }
Re:The Next Step for Generics by joshuamorton on Tuesday June 16, 2020 @05:20PM (#23544307)
Ah you're quite correct.
Re:The Next Step for Generics by grandmczeb on Tuesday June 16, 2020 @05:04PM (#23544087)
Yes you can? The equivalent type in C++ is std::expected[1] which doesn't even contain a pointer that could be dereferenced (unless T is a pointer obviously).

[1] unfortunately not standardized yet https://github.com/TartanLlama/expected

Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @05:17PM (#23544262)
Who are you replying to? Is it in any way related to the original comment I replied to and this type?

    class Result<T>
    {
      bool IsSuccess {get; set;}
      string Message {get; set;}
      T Data {get; set;}
    }
Re:The Next Step for Generics by grandmczeb on Tuesday June 16, 2020 @05:21PM (#23544335)
I am replying to you and its pretty obviously related to your comment.

You: "C++, Java, and so on have had generics for ages and with types like the one above, null pointer exceptions are incredibly common."

jcelerier: "you'd never get a null-pointer exception in C++ given the type that OP mentioned."

You: "Then you can't construct it unless it's successful, no?"

Me: "The equivalent type in C++ [to what the OP mentioned] is std::expected". It is not possible to get a null-pointer exception with this type and yet you can construct it.

Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @05:33PM (#23544480)
It sounds quite a lot like you took the type the OP posted and changed it in your reply to a different type that isn't standardized yet, do I have that right?
Re:The Next Step for Generics by grandmczeb on Tuesday June 16, 2020 @05:37PM (#23544523)
The code the OP posted is not C++. If you translate it to C++ there is no way to get a null pointer exception.

It sounds quite a lot like you're looking to be pointlessly argumentative, do I have that right?

Re:The Next Step for Generics by AaronFriel on Tuesday June 16, 2020 @06:25PM (#23545056)
There are two things being discussed in this thread.

1. The first, my original point was that a high quality type system enforces correctness by more than just having generics. There's no proper way in C++ to create this class and make a sum type - there's no pattern matching or type narrowing like can be done in languages with more interesting type systems and language facilities. Generics is just a first step to a much more interesting, safer way of writing code.

2. The second, my replies to folks who have corrected me, and I'll borrow your little paraphrase here:

> [Me]: "C++, Java, and so on have had generics for ages and with types like the one above, null pointer exceptions are incredibly common."

>

> jcelerier: "you'd never get a null-pointer exception in C++ given the type that OP mentioned."

>

> [Me]: "Then you can't construct it unless it's successful, no?"

I think this is exactly correct still. If it's impossible to create an instance of Result<T> without... well, a successful result, you may as well just typedef Result<T> to T, right? If it can't store the "failure" case, it's totally uninteresting.

If it _can_ store the failure case, making it safe in C++ is fairly challenging and I dare say it will be a little longer and a little less safe than a Result I can write in a few lines of TypeScript, Scala, Rust, an ML or Haskell derivative, and so on.

Now, I'd love to be proven wrong, I haven't written C++ for a while so the standard may have changed, but is there a way to write a proper enum and pattern match on the value?

It looks like this std::expected thing is neat, but can a _regular person_ write it in their own code and expect it to be safe? I can say with certainty that I can do that for the languages I listed above and in fewer than 10 lines of code.

The C++ answer to that is, well, this:

https://github.com/TartanLlama/expected/blob/master/include/...

I don't think it's a comparison.

Re:The Next Step for Generics by jcelerier on Wednesday June 17, 2020 @04:12AM (#23549040)
> The C++ answer to that is, well, this:

the linked link has a ton of things that are "quality-of-life" things. For instance comparing two Result values efficiently (you don't want to compare two Result<T> bitwise, and you don't want the "is_valid" flag to be first in the structure layout to fallback on the automatic default of lexical order as that would sometimes waste a few bytes, but you want the "is_valid" flag to be the first thing being compared for instance. Do you know of a language that would do that automatically ?).

It also supports back to C++11 and GCC4.9 with various fixes for some specific compiler versions's bugs, supports being used with -fno-exceptions (so a separate language than ISO C++) - sure, today's languages can do better in terms of prettiness, but so would a pure-C++20 solution that only needs to work with a single implementation.

If you are ready to forfeit some amount of performance, for instance because you don't care that the value of your Result will be copied instead of moved when used in a temporary chain (e.g. `int x = operation_that_gets_a_result().or_else([] (auto&& error) { return whatever; });` 3/4 of the code can go away (and things will still likely be faster than most other languages).

Re:The Next Step for Generics by nine_k on Tuesday June 16, 2020 @04:36PM (#23543759)
Well, T can be a pointer / reference here.
Re:The Next Step for Generics by jcelerier on Tuesday June 16, 2020 @06:20PM (#23545005)
That wouldn't change anything to Result<T>'s implicit safety properties. "safe + unsafe == unsafe" - to have a meaningful discussion we should focus on the safe part, else it's always possible to bring up the argument of "but you can do ((char*)&whatever)[123] = 0x66;"
Re:The Next Step for Generics by polskibus on Tuesday June 16, 2020 @05:27PM (#23544403)
With c# 8 you have nullable references and you can use the compiler to guard you against null pointer exceptions.
Re:The Next Step for Generics by masklinn on Tuesday June 16, 2020 @05:05PM (#23544113)
> That's a generic container of 0 or 1 elements ;)

Then chances are so are most if not all of the uses of generics OP criticises. The only "non-container" generics I can think of is session types where the generic parameter represents a statically checked state.

Re:The Next Step for Generics by jasonhansel on Tuesday June 16, 2020 @05:16PM (#23544260)
Result types are much better than multiple return values. But now the entire Go ecosystem has to migrate, if we want those benefits (and we want consistent behavior across APIs). It'd be like the Node.js move to promises, only worse...
Re:The Next Step for Generics by lenish on Tuesday June 16, 2020 @04:18PM (#23543559)
I'm not sure why you'd use a class like this in Go when you have multiple returns and an error interface that already handles this exact use case.
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @04:50PM (#23543919)
Because multiple return values for handling errors is a strictly inferior and error prone way for dealing with the matter.
Re:The Next Step for Generics by lenish on Tuesday June 16, 2020 @06:37PM (#23545156)

    func foo() (*SomeType, error) {
        ...
        return someErr
    }

    ...
    result, err := foo()
    if err != nil {
        // handle err
    }
    // handle result
vs

    type Result struct {
        Err error
        Data SomeType
    }

    func (r *Result) HasError() bool {
        return r.Err != nil
    }

    func bar() *Result {
        ...
        return &Result { ... }
    }

    ...
    result := bar()
    if result.HasError() {
       // handle result.Err
    }
    // handle result

I'm not really sure I see the benefit to the latter. In a language with special operators and built-in types it may be easier (e.g. foo()?.bar()?.commit()), but without these language features I don't see how the Result<T> approach is better.
Re:The Next Step for Generics by et1337 on Tuesday June 16, 2020 @06:56PM (#23545342)
Go can't really express the Result<T> approach. In Go, it's up to you to remember to check result.HasError(), just like it's up to you to check if err != nil. If you forget that check, you'll try to access the Data and get a nil pointer exception.

The Result<T> approach prevents you from accessing Data if you haven't handled the error, and it does so with a compile-time error.

Even with Go's draconian unused variable rules, I and my colleagues have been burned more than once by forgotten error checks.

Re:The Next Step for Generics by jatone on Tuesday June 16, 2020 @08:49PM (#23546338)
there are linters that will help you with that.

https://github.com/kisielk/errcheck

https://golangci-lint.run/usage/linters/ has a solid set of options.

Re:The Next Step for Generics by nimish on Wednesday June 17, 2020 @12:47AM (#23547906)
I just wish the linter was integrated into the compiler. And that code that didn't check would simply not compile
Re:The Next Step for Generics by mrkeen on Wednesday June 17, 2020 @11:55AM (#23552873)
> without these language features I don't see how the Result<T> approach is better.

That's the point! I want language features!

I don't want to wait 6 years for the designers to bake some new operator into the language. I want rich enough expression so that if '?.' is missing I just throw it in as a one-liner.

Generics is one such source of richness.

Re:The Next Step for Generics by whateveracct on Wednesday June 17, 2020 @03:47AM (#23548901)
A language with sun types will express Result as Success XOR Failure. And then to access the Success, the compiler will force you to go through a switch statement that handles each case.
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @11:55PM (#23547586)
The alternative is not the Result type you defined, but something along the lines of what languages like Rust or Haskell define: https://doc.rust-lang.org/std/result/
Re:The Next Step for Generics by californical on Tuesday June 16, 2020 @05:03PM (#23544084)
It's interesting that you say this, because I've had the opposite experience. I wouldn't say it's strictly inferior, because there are definitely upsides. If it was strictly inferior, why would a modern language be designed that way -- there must be some debate right?

I love multiple returns/errors. I find that I never mistakenly forget to handle an error when the program won't compile because I forgot about the second return value.

I don't use go at work though, I use a language with lots of throw'ing exceptions, and I regularly miss handling exceptions that are hidden in dependencies. This isn't the end of the world in our case, but I prefer to be more explicit.

Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @05:06PM (#23544120)
> If it was strictly inferior, why would a modern language be designed that way

golang is not a modern language (how old it is is irrelevent), and the people who designed it did not have a proper language design background (their other accomplishments are a different matter).

Having worked on larger golang code bases, and I've seen several times where errors are either ignored or overwritten accidentally. It's just bad language design.

Re:The Next Step for Generics by dgb23 on Tuesday June 16, 2020 @06:47PM (#23545255)
I cannot think of a language where errors cannot be ignored. In go it is easy to ignore them, but they stick out and can be marked by static analysis. The problems you describe are not solved at the language level, but by giving programmers enough time and incentives to write durable code.
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @08:55PM (#23546402)
The following line in golang ignores the error:

    fmt.Println("foo")
Compare to a language with exception handling where an exception will get thrown and bubbles up the stack until it either hits a handler, or crashes the program with a stack trace.

And I was referring to accidental ignoring. I've seen variations of the following several times now:

    res, err := foo("foo")
    if err != nil { ... }
    if res != nil { ... }
    res, err = foo("bar")
    if res != nil { ... }
Re:The Next Step for Generics by Mawr on Tuesday June 16, 2020 @11:07PM (#23547298)
Usage of linters fixes this:

>The following line in golang ignores the error:

   fmt.Println("foo")
fmt.Println() is blacklisted for obvious reasons, but this:

    a := func() error {
        return nil 
    }
    a()
results in:

    go-lint: Error return value of 'a' is not checked (errcheck)
>And I was referring to accidental ignoring. I've seen variations of the following several times now:

    res, err := foo("foo")
    if err != nil { ... }
    if res != nil { ... }
    res, err = foo("bar")
    if res != nil { ... }
results in:

    go-lint: ineffectual assignment to 'err' (ineffassign)
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @11:50PM (#23547550)
> fmt.Println() is blacklisted for obvious reasons

That's the issue with the language, there are so many special cases for convenience sake, not for correctness sake. It's obvious why it's excluded, but it doesn't make it correct. Do you want critical software written in such a language?

Furthermore, does that linter work with something like gorm (https://gorm.io/) and its way of handling errors? It's extremely easy to mis-handle errors with it. It's even a widely used library.

Re:The Next Step for Generics by geodel on Tuesday June 16, 2020 @11:02PM (#23547261)
Huh, I have seen enough catch blocks in Java code at work which are totally empty. How is that better than ignoring error?
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @11:51PM (#23547558)
Because it's an explicit opt-in, as opposed to accidental opt out. And static checking can warn you about empty catch blocks.
Re:The Next Step for Generics by umanwizard on Tuesday June 16, 2020 @11:11PM (#23547318)
In rust, errors are difficult to ignore (you need to either allow compiler warnings, which AFAICT nobody sane does, or write something like `let _ = my_fallible_function();` which makes the intent to ignore the error explicit).

Perhaps more fundamental: it’s impossible to accidentally use an uninitialized “success” return value when the function actually failed, which is easy to do in C, C++, Go, etc.

Re:The Next Step for Generics by ori_b on Wednesday June 17, 2020 @12:03AM (#23547639)
Or .unwrap(), which I see relatively often.
Re:The Next Step for Generics by umanwizard on Wednesday June 17, 2020 @08:43AM (#23550684)
That’s not ignoring errors, it’s explicitly choosing what to do in case of one (crash).
Re:The Next Step for Generics by fooster on Tuesday June 16, 2020 @06:06PM (#23544866)
Error handling is hard, period. Error handling in go is no worse than any other language, and in most ways it is better being explicit and non-magic.

> people who designed it did not have a proper language design background

Irrelevant.

> It's just bad language design.

try { ... } catch(Exception ex) { ... }

Re:The Next Step for Generics by entha_saava on Wednesday June 17, 2020 @12:06AM (#23547657)
Exceptions don't lead to silent but dangerous and hard to debug errors. The program fails if exception is not handled.
Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @09:03PM (#23546452)
> try { ... } catch(Exception ex) { ... }

The error here is explicitly handled, and cannot be accidentally ignored. Unlike golang where it's quite easy for errors to go ignored accidentally.

Re:The Next Step for Generics by fooster on Tuesday June 16, 2020 @09:42PM (#23546751)
Nevertheless, this is how it is mostly done in Java. I haven't used eclipse in eons, but last time I did it even generated this code.

If you care with go, use errcheck.

Re:The Next Step for Generics by apta on Wednesday June 17, 2020 @12:02AM (#23547631)
Does errcheck work well with gorm (https://gorm.io/) and it's way of returning errors? This is not an obscure library, it's quite widely used.
Re:The Next Step for Generics by ori_b on Wednesday June 17, 2020 @12:24AM (#23547771)
Does any language save you from explicitly screwing up error handling? Gorm is doing the Go equivalent of:

     class Query {
         class QueryResult {
             Exception error;
             Value result;
         }
         public QueryResult query() {
             try {
                 return doThing();
             } catch(Exception e){
                 return new QueryResult(error, null);
             }
         }
     }
Gorm is going out of its way to make error handling suck.
Re:The Next Step for Generics by apta on Wednesday June 17, 2020 @03:46PM (#23555856)
> Does any language save you from explicitly screwing up error handling?

It's about the default error handling method being sane. In exception based languages, an unhandled error bubbles up until it reaches a handler, or it crashes the program with a stacktrace.

Compare to what golang does, it's somewhat easy to accidentally ignore or overwrite errors. This leads to silent corruption of state, much worse than crashing the program outright.

Re:The Next Step for Generics by ori_b on Wednesday June 17, 2020 @05:14PM (#23556859)
> It's about the default error handling method being sane.

Gorm isn't using the default error handling.

Re:The Next Step for Generics by apta on Wednesday June 17, 2020 @07:21PM (#23558019)
That's one point in this discussion. The language allows error handling that way. Compared to a language with proper sum types or exceptions, where one would have to actively work against the language to end up with that mess.
Re:The Next Step for Generics by ori_b on Wednesday June 17, 2020 @08:26PM (#23558471)
> That's one point in this discussion. The language allows error handling that way. Compared to a language with proper sum types or exceptions, where one would have to actively work against the language to end up with that mess.

I've seen a bunch of code that does the equivalent of the Java I posted above. Mostly when sending errors across the network.

Re:The Next Step for Generics by hactually on Tuesday June 16, 2020 @09:11PM (#23546512)
because it has try/catch. Without that (which would be similar to not checking the err in go) it explodes or throws to a layer up that may not expect it.

Each language has its wonks.

Re:The Next Step for Generics by apta on Tuesday June 16, 2020 @11:53PM (#23547572)
> Without that (which would be similar to not checking the err in go) it explodes or throws to a layer up that may not expect it.

It's not similar to that at all. Without it, the exception bubbles up until it gets caught somewhere, or crashes the program with a useful stacktrace.

With golang, it just goes undetected, and the code keeps running with corrupt state, without anyone knowing any better.

Re:The Next Step for Generics by dgb23 on Tuesday June 16, 2020 @06:41PM (#23545193)
I would say it is a very ergonomic way of doing this. It allows for writing in a more exploratory way until you know what your error handling story is. Then, even if you choose to propagate it later, you just add it to your signature. Also it is very easy to grok and clear. Definitely not strictly inferior.
Re:The Next Step for Generics by erik_seaberg on Tuesday June 16, 2020 @04:45PM (#23543867)
It's a lot cleaner to pass a Result<T> through a channel or a slice than to create two channels or slices and confirm everyone's following the same convention when using them.
Re:The Next Step for Generics by lenish on Tuesday June 16, 2020 @06:14PM (#23544944)
I concede that there are probably scenarios where this design makes sense within that context. I typically find that either I care about a single error and terminating the computation, or I don't care about errors at all. In the former case, the primitives in the sync package (or just an error channel which we send to once and close) are adequate. The latter case presents no issues, of course.

At $work we definitely have examples where we care about preserving errors, and if that tool were implemented in Go a solution like a Result struct containing an error instance and a data type instance could make sense.

Re:The Next Step for Generics by lmm on Tuesday June 16, 2020 @08:27PM (#23546160)
It has a bunch of invalid states (message and data both set, neither set, message set but IsSuccess is true, etc.). So you have to either check it every time, or you'll get inconsistent behaviour miles away from where the actual problem is. It's like null but even more so.
Re:The Next Step for Generics by dragonwriter on Tuesday June 16, 2020 @07:31PM (#23545642)
Well, for one thing, it doesn't actually work like a proper Optional<T> or Either<T, string> type. It works more like Either<(T, string),(T, string)>, which might have some uses, but isn't typically a thing someone would often reach for if they had a type system that readily supported the other two options.
Re:The Next Step for Generics by alkonaut on Wednesday June 17, 2020 @05:35AM (#23549524)
> What's wrong with this?

That it's mutable, at the very least!

Re:The Next Step for Generics by londons_explore on Tuesday June 16, 2020 @04:16PM (#23543541)
I feel like such a class should either be part of the language, and part of language idioms etc, or it shouldn't be used.
Re:The Next Step for Generics by tomjen3 on Tuesday June 16, 2020 @04:26PM (#23543643)
Can you articulate why? it seems to me that 'feel' should not be part of the discussion.
Re:The Next Step for Generics by lenish on Tuesday June 16, 2020 @06:20PM (#23545001)
Not GP, but I've sometimes found libraries implementing similar concepts differently causing issues.

E.g.

    libraryA.Result struct {
        Err error
        Data SomeDataType
    }

    libraryB.Result struct {
        err string
        Data SomeDataType
    }
    func (r libraryB.Result) Error() string {
         return r.err
    }
Now you have two different implementations of the same fundamental idea, but they each require different handling. In Go, where many things simply return an error type in addition to whatever value(s), you would now have three different approaches to error handling to deal with as opposed to just whatever the language specified as the best practice.
Re:The Next Step for Generics by mrkeen on Wednesday June 17, 2020 @11:58AM (#23552895)
This is what interfaces are for.

Let your caller bring their own error type and instantiate your library code over that.

Re:The Next Step for Generics by juststeve on Tuesday June 16, 2020 @05:18PM (#23544282)
Not GP but:

It may frustrate coworkers who need to edit the code.

It adds another dependency into your workflow.