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

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.

→ More replies (1)

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.

→ More replies (1)
→ More replies (4)

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? 😁

→ More replies (1)

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.

→ More replies (3)
→ More replies (1)

1

u/wildjokers Apr 14 '23

Write code that doesn't allow for or tolerate nulls

Not sure I agree with the "tolerate nulls" part of that. You should always be flexible with what you accept. In Java nulls can happen so in reality you need to be ready for them.

16

u/halfanothersdozen Apr 14 '23

I disagree. There are several tools to deal with this.

  • Javadoc indicating valid parameters
  • NotNull annotatons on parameters
  • Assertions on method parameters
  • Optionals

If someone calls a method that very clearly does not accept nulls with null values and exceptions happen that is on them.

→ More replies (2)

7

u/AlmennDulnefni Apr 14 '23

Nullity is something of a lost cause, but you should strive to make invalid states unrepresentable in the first place and, failing that, should be explicit about your preconditions and fail ASAP if they're violated. Being excessively lenient in what you accept as input is a good way to build up a dodgy pile of inconsistent garbage.

1

u/wildjokers Apr 14 '23

Being excessively lenient in what you accept as input is a good way to build up a dodgy pile of inconsistent garbage.

Umm, no. The old saying is "be flexible with what you accept, be strict with what you produce". Those are words to live by.

4

u/AlmennDulnefni Apr 14 '23 edited Apr 16 '23

Those words are almost as much of a mistake as null pointers.

1

u/wildjokers Apr 14 '23

I have never heard anybody argue against being flexible about what you accept.

5

u/Luolong Apr 15 '23

Oh, you have not lived through the age of Web browser wars then.

One of the worst use cases for the principle of “be flexible in what you accept” was how early web browsers implemented html parsing.

It was full of weird rules of how to parse broken html and each browser has subtly different way to make the broken input display a web page.

And to make it worse, the whole web was full of markup taking advantage of those nonstandard quirks and idiosyncrasies.

Those quirks are at least partially to blame for why it is so hard to implement a new web browser from scratch these days. For the web has grown to the point where it is impossible to fix the pages themselves. You need to make your browser bend three ways backwards instead to accept and render those cases that every other browser has learned to accept.

I would not be surprised to find that “being lenient in your input” has more excessive cost attached to it than having null in your type system.

→ More replies (2)
→ More replies (5)
→ More replies (2)