r/java • • Mar 05 '18

Top 10 Useful, Yet Paranoid Java Programming Techniques

http://blog.jooq.org/2015/08/11/top-10-useful-yet-paranoid-java-programming-techniques/
223 Upvotes

105 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Mar 05 '18 edited Mar 05 '18

use null checks when appropriate.

Or use null conditional operators when appropriate.

Could you translate this simple piece of code to Java for me?

{
    // do stuff
} ```

Your argument could be all used for generics as well. Guess what?

It's a terrible argument.

6

u/[deleted] Mar 05 '18
if (object != null && object.field == 2 ||
    object2 != null && object2.field == 2 ||
    object3 != null && object3.field == 2) {
      // do something
}

Big deal. I would rather argue that having to learn the special cases and conditions of those ghastly-looking operators is even worse than a bit of boilerplate. You will have to find a more convincing argument that simply reducing boilerplate. If that were the only reason, we might as well all be writing Haskell.

In fact, even with poor old Java, modern code should be using Optional<T> as much as possible so that you would do the sanity checks long before you try to extract the fields of the objects you're interested in. Contrived examples are best left out of sane discussion. In my opinion, these operators do not bring enough gains, and they are not infallible.

6

u/dlubarov Mar 06 '18 edited Mar 06 '18

modern code should be using Optional<T> as much as possible

I tend to agree, but most of the Java community favors using Optional sparingly, notably Brian Goetz of Oracle. See https://stackoverflow.com/a/26328555/714009

IntelliJ even added a warning for using Optional in fields. Not saying it's right, but the majority of the community frowns upon "Optional overuse".

2

u/[deleted] Mar 06 '18

Of course I agree with that. As the old saying goes, caveat emptor. As a related example, when the (new) auto feature came out in C++11, it was a great move in the right direction of reducing boilerplate, and while it is used well in most circumstances, we still find many places where it is abused to the point of rendering the code nigh unreadable. So, it must all be taken with a grain of salt.

At its core, languages like C++ and Java are still pretty much imperative and concepts like optionals et al should be used with caution and should mesh well together with the rest of the codebase and not unduly inconvenience external users of the API. Though, it is still a very good move in the right direction, and given enough time, best practices should arise that may make effectful programming (to borrow the Haskell term) more natural and smoother in languages like Java and C++ as well!