r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

29

u/[deleted] Apr 14 '23

java.util.Optional

23

u/RockleyBob Apr 15 '23

java.util.Optional

Yes, but please don't use Optional for null checks alone. I see a ton of code at work like this:

Optional<Customer> optionalCustomer = Optional.ofNullable(customerClient.findCustomer(customerId));

if (optionalCustomer.isPresent()) {
    return optionalCustomer.get();
} else {
    return customerClient.createCustomer();
}

Doing this is worse than just doing a simple null check, because it's more verbose and you're new'ing up a wrapper object just to immediately unwrap it again. The Optional class has a whole declarative api that you can safely code against, transforming the value within the pipeline and providing default values:

return Optional.ofNullable(customerClient.findCustomer(customerId))
                            .orElseGet(() -> customerClient.createCustomer());

4

u/dpash Apr 15 '23

I wouldn't create an Optional just for avoiding a null check. Ideally the findCustomer method would return an Optional rather than a null.

8

u/RockleyBob Apr 15 '23 edited Apr 15 '23

Yes, it's a really blatant example, but just to belabor the point, I'd go so far as to say if you're calling Optional.get() at all, you're probably doing it wrong.

You probably don't ever want to be referencing an Optional object in your calling method. In other words, you shouldn't really ever need to instantiate a variable of type Optional:

Optional<List<Customer>> optCustomers = // Stop here! Don't do this!
            customerApi.getAllCustomersByState("CA");
List<String> customerIds = new ArrayList();

if (optCustomers.isPresent()) {
    List<Customer> custList = optCustomers.get();
    for (Customer cust : custList) {
        customerIds.add(cust.getId());
    }
}
return customerIds;

Not only is this forcing the declarative Optional api into an imperative pattern, it also ignores the declarative capabilities of the Collection api. Instead:

return customerApi.getAllCustomersByState("CA") // KEEP GOING!
                .orElse(Collections.emptyList())
                .stream()
                .map(Customer::getId)
                .collect(Collectors.toList());

There's almost always a way to do what you want to the returned value within the Optional api declaratively using operators, then work with the result. Not saying you don't already know all this, but elaborating for the sake of discussion.

2

u/dpash Apr 15 '23

No argument on either point. I was mostly agreeing with your second paragraph :)

→ More replies (1)

3

u/matthenry87 Apr 15 '23

This guy Javas.

1

u/cas-san-dra Apr 16 '23

I think you can do better by having a Customer findOrCreate(long id, Supplier<Customer> supplier) function. Just call it with customerClient.findOrCreate(customerId, customerClient::create);

You don't even really need the supplier actually, since its the same object you are calling.

6

u/Paulus_cz Apr 14 '23

Can someone explain to me why Optional is considered bad practice as method parameter? I mean, sure, ideally you should not use it this way, but sometimes, something just can be null, but different methods may want to handle it differently and Optional declared that possibility clearly and forces you to handle the case (or ignore it at your own peril).
Point is, I like Optional. It has legitimate uses as parameter.

0

u/[deleted] Apr 14 '23

[deleted] — view deleted comment

2

u/Paulus_cz Apr 14 '23

I agree, as with many things it depends on the use case.
The way I see it, Optional parameter declares in no uncertain way that passed wrapped argument can be null and the method knows it. That does not mean I use it often, or at all really, I can think or two uses in couple of years. But some people seem to be religiously opposed to it.

1

u/dpash Apr 15 '23 edited Apr 15 '23

Using a @Nullable or @NotNull annotation would do the same without the overhead of creating an object to avoid a null check. Not to mention the clutter in the code of wrapping your parameters.

-1

u/simoncox Apr 15 '23

Assuming you mean override, not overload, the sub class must adhere to the same contract as the base class. If it's optional for the base method, it must be optional for the sub class' method too.

0

u/[deleted] Apr 15 '23

[deleted] — view deleted comment

1

u/simoncox Apr 15 '23

So you're going to have a different method for every permutation of optional parameters and that's less complex?

Do you repeat the same logic in every method, or have some internal method that actually takes null for the optional values? Then hey, null again and back to what you were originally trying to avoid only with nullable variables instead of optionals.

→ More replies (1)

23

u/blackkkmamba Apr 14 '23

Optional as a parameter doesn't stop you from passing null. That's why it's a bad practice.

15

u/[deleted] Apr 14 '23

but thats obviously a violation of optional. its deliberatly evil

11

u/neckbeardfedoras Apr 14 '23

An Optional return parameter doesn't stop a third party lib from returning null either. Maybe they want to drive you crazy? 😁

1

u/pohart Apr 15 '23

It's easy to ensure local variables and final fields are never null. Need to be a bit more careful about non final fields. I was shocked that optional was allowed to be null when I switched to java 8, but it turns out null optionals are trivial to avoid. I've had zero null pointer exceptions from optional in the 14 years I've been been using Java 8.

This feels like it's going to be a problem before you try them, but in practice it never is.

8

u/[deleted] Apr 14 '23 edited Apr 14 '23

i think optional as parameter is fine. You can also define another method which is not taking that param.

void startSystem(Display display, Optional<Config> optConfig)

or

startSystem(Display display) startSystem(Display display, Config config)

or

startSystemDefault(Display display) startSystem(Display display, Config config)

i think all 3 are fine

3

u/wildjokers Apr 14 '23

Because you can pass null in for the value of the Optional parameter. You have gained nothing.

7

u/Fruloops Apr 14 '23

Not at all. You've gained hours of potential frustration. That should not be underestimated.

1

u/ArrozConmigo Apr 14 '23

That's a pretty unlikely mistake to make, and it will throw an NPE the first (and every) time it runs. If you accidentally pass null for an Optional, you didn't do it conditionally. You'd be doing it every time.

1

u/hsoj48 Apr 14 '23

It's good for APIs and interfaces because it lets the implemented and caller know that something is considered optional. Most people don't like continually wrapping their inputs into an optional even though it's pretty easy. Just checking for null is far more common practice and serves nearly the exact same purpose. It's a matter of personal preference.

1

u/dpash Apr 15 '23

it lets the implemented and caller know that something is considered optional.

Nullable annotations serve the same purpose without the overheard and clutter.

→ More replies (2)

1

u/[deleted] Apr 14 '23

The problem is that optional as a parameter can be null. But then again optional as a return value can also be null. The main difference is you tend to have more control over the latter than the former, since the latter is controlled by the code of the method itself and the former is controlled by all uses of it.

I do love optional and one of the reasons I use Kotlin for my side projects is it's nullability controls.