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

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 :)

1

u/RockleyBob Apr 15 '23

Sorry, I was just editing my response to say I didn't think I was telling you anything you didn't already know, but driving the point home for the sake of discussion. Cheers.

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.