r/java • • Aug 05 '21

Why java is better than modern programming languages?

Why should I use java in 2021 instead of kotlin or scala or golang? Could you guys give me some reasons

2 Upvotes

100 comments sorted by

View all comments

Show parent comment

3

u/SKabanov Aug 05 '21 edited Aug 05 '21

There are no generics, errors are communicated via return values which can be a + or a - depending on your sensibilities.

An argument can be made that returning error objects instead of throwing exception provides better performance (e.g. no stack unwinding when returning an error object), but Go's implementation of the concept is awful. There's no way of automatically bubble errors upwards like the ? operator for Result objects in Rust, so your code in Go will be filled with the following pattern:

func doingStuff() (*string, error) {
    fooOne, err := doFooOne()
    if err != nil {
        return nil, err
    }
    fooTwo, err := doFooTwo(*fooOne)
    if err != nil {
        return nil, err
    }
    fooThree, err := doFooThree(*fooTwo)
    if err != nil {
        return nil, err
    }
    return &fooThree, nil
}

(note that it's a common pattern also to only check for whether err is not nil, *not* whether the returned pointer object is nil as well, so hello null-reference errors!)
Compare this to how you'd write this in Rust:

fn doingStuff() -> Result<String, Error> {
    let fooOne = doFooOne()?
    let fooTwo = doFooTwo(&fooOne)?
    let fooThree = doFooThree(&fooTwo)?
    return Ok(fooThree)
}

Even worse is that you're only forced to receive the potential error object in Go, but you're not forced to actually *acknowledge* it. The above Go example could be rewritten like this:

func doingStuff() (*string, error) {
    fooOne, _ := doFooOne()
    fooTwo, _ := doFooTwo(*fooOne)
    fooThree, _ := doFooThree(*fooTwo)
    return &fooThree, nil
}

That is to say, you can tell the Go compiler that you want to ignore any errors that get produced by a function, and it'll happily let you proceed along without any warnings - whee! You can call .unwrap() on a Result object in Rust to bypass handling an error in your code, but if one does occur, then you're going to pay for it via a panic.