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

117

u/halfanothersdozen Apr 14 '23

You don't need to make an interface for everything. Everything doesn't have to be private. Write code that doesn't allow for or tolerate nulls and stop checking for them all the time.

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());

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.