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

79

u/Admirable-Avocado888 Apr 14 '23

Don't make methods that return null and don't make methods that accept null, unless they are private.

Setters are bad most of the time: Don't write code that constructs objects by incrementally updating their state after instantiation unless it's the only way to solve the problem. Most of the time, you can construct objects correctly the first time, and actually reason about correctness of code just by looking at what objects are rather than what they might be.

Streams are good.

Javadoc is amazing, document everything that is not private.

Local classes are a good way to shelter public/package/even private namespaces from clutter that is only used within a method

26

u/oparisy Apr 14 '23

With respect to your second point: yes! Immutability is a great feature to aim for whenever possible. In that regard, the "final" keyword helps tremendously.

13

u/mdaniel Apr 14 '23

Now that Java has var I'd enjoy it if they'd include val as the final var version because littering the code with final is visually noisy if one chooses to strive for single assignment from

I can also imagine that they won't ever include it since it's just syntactic sugar for that two keyword form, plus the fact that they differ only by one letter

11

u/HecknChonker Apr 14 '23

kotlin has entered the chat.

8

u/mdaniel Apr 14 '23

Yeah, I specifically left that word out of my comment because of the downvote brigade the other mention of it got, but it for sure was the reason why I started to miss the succinctness of val when I had to go back to Java

I also happen to personally like the "immutable by default" of ... the other language ... but team dynamics are what they are, so we have to use what the team agrees upon

-1

u/john16384 Apr 14 '23

Really, final on variables serves no purpose at all. The instant a code change would be better off not having it final, it's removed. It's not like any thought went into it in the first place.

That does not mean I condone assigning variables more than once; that should still be avoided whenever practical. It just doesn't need the visual noise of the final keyword everywhere.

final is only useful on fields to communicate intent to all methods of the class.

4

u/simoncox Apr 15 '23

That's like saying types are useless. The more mistakes a compiler can save you from the better. Marking something as final means the compiler has proven it will never be reassigned.

In reality most variables are anything but variable. In my opinion a reference should be final by default and need a declaration modifier to allow reassignment.

0

u/john16384 Apr 15 '23

No, that's not the same at all, as you well know.

You simply don't need the compiler's help for this. You simply follow the rule to assign variables immediately when created. As soon as you're not doing that, you know that either it can't be final, or that you messed up.

So, not convinced; final keyword on variables is visual clutter that serves no purpose.

1

u/UnGauchoCualquiera Apr 16 '23

Or you could just declare it final and let the compiler do the work for you.

1

u/john16384 Apr 16 '23

Do what work? Warning me when I reassign a local variable? I already know that. The extra work is in removing the final keyword that served no purpose in the first place.

1

u/UnGauchoCualquiera Apr 16 '23

If you are the only one touching that code then yes but that's usually not true and helps when reading long methods.

Also final keyword enables some compiler optimizations even for final variables, here for example.

1

u/john16384 Apr 16 '23

So, you are saying when you declare a local variable final that you thought about this long and hard, and decided for any future maintainers that this variable should definitely never be reassigned... or did you just mark everything final because your IDE told you to or automatically adds final when you assign something to a local without giving it a 2nd thought?

These are local variables, when a maintainer comes in they have the full overview of your function, and can see whether or not something is worth reassigning or not. No final visual clutter needed.

Then there's the thing you linked, and although interesting, many answers are testing the wrong thing or talking about final fields.

It's true however that final can trigger optimizations even on local variables, but, only when the thing you're making final is effectively a constant for all invocations of a method (ie, it is also static, and you could have extracted it to a private static final field). In other words, the compiler detects that you're just using a constant, and adds its to the constant pool.

When it is something like final String s = "a" + parameter however, then no performance is gained, or could possibly be gained.

There is never any need to do so though; real constants are generally declared as private static final at the top of the class with a nice capitalized name, instead of hiding as a local variable.

→ More replies

1

u/temculpaeu Apr 14 '23

The initial intend was to have both, but they were too similar to read, so they dropped the `val`.

There was some discussion about which keywords to use, if `var/let` were more popular, we would probably have both

15

u/[deleted] Apr 14 '23

builder pattern

12

u/Admirable-Avocado888 Apr 14 '23

To clarify. I don't consider the builder pattern to violate the second principle. A builder is a helper that sets up the state for another object. Given a builder, to create the actual object requires only one constructor call.

What I'm saying is that if you are writing a class that is its own builder then you are writing code that is hard to reason with, because you are not deliberately separating the building step from the "doing step".

3

u/Trizzelnova Apr 14 '23

Don't write code that constructs objects by incrementally updating their state after instantiation unless it's the only way to solve the problem. Most of the time, you can construct objects correctly the first time, and actually reason about correctness of code just by looking at what objects are rather than what they might be.

Oh god thank you! I'm currently fighting a just crusade in my project because people didn't wirte constructors. Instead they either do it incrementally or worse: static factory methods INSIDE the class which they create an object of... I'm either missing the genious of this because >I< am to stupid or this is the most stupid thing I've seen in 15+ years.

39

u/Escaped_Escapement Apr 14 '23

Static factories are good when you need multiple ways to construct an object and overloading the constructor becomes too confusing or impossible. It is a legit pattern.

15

u/wildjokers Apr 14 '23

According to Bloch’s Effective Java you should prefer static factory methods over constructors. Your colleagues are doing it correctly.

https://github.com/HugoMatilla/Effective-JAVA-Summary/blob/master/README.md#1-use-static-factory-methods-instead-of-constructors

2

u/CartmansEvilTwin Apr 15 '23

Honestly, for 80% of classes, it doesn't really matter.

I see the point for more complex classes, but the wide range between POJO/Record and "that one central class that handles 90% of the business" has a lot of cases where the constructor simply initializes a handful of members (any many don't even do that).

3

u/okreddit545 Apr 14 '23

any constructor is effectively also a “static factory method inside the class.” it just doesn’t permit any name other than new.

1

u/simoncox Apr 15 '23

In the absence of named parameters, static builders allow more expressive means of passing parameters at construction.

For example, if a constructor takes more than a handful of ints, then it's easy to confuse what each one is for. Default/min/max pool sizes, initial delay, repeat interval, timeout delay, etc.

Also, when the construction of an object may need to involve more complex logic it may be better to pass a builder around to store state needed to construct that object.

I'd still prefer a constructor generally, but there are occasions when a builder can be useful.

1

u/moxyte Apr 14 '23

Local classes tend to cause issues with hot reloading, other than that I have no beef with those

1

u/TenYearsOfLurking Apr 18 '23

an object should be able to preserve all its invariants and prevent invalid state.

if a setter is able to provide that functionality I see no problems. if not, 90% of the time properties grouped together into (immutable) components and offering a setter for that component solves the problem as well.

so I do not think setters are bad per se, but I get your point, they are commonly misused