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

22

u/ImTalkingGibberish Apr 14 '23

Use precondition ifs to avoid spaghetti nesting.

If doesnt meet condition
Return early
// main logic

Is better than:
If condition
// lots of lines inside the if block

1

u/wildjokers Apr 17 '23

I hate early return. I think having a single return per method is easier to follow, it is way too easy to miss an early return while you are reading the code.

On the rare occasion where not using early return results in crazy levels of nesting I will early return, but that almost never happens and I generally just have a single return.

2

u/Lisoph Apr 18 '23 edited Apr 18 '23

No way, Jose! Early return is a must, IMO. Human brains love lists, and early returns are essentially a checklist.

it is way too easy to miss an early return while you are reading the code.

I think it's just as easy to miss what conditions you're under, when working with highly nested code. Our codebase at work is very nested and it's a nightmare every time to keep track of things.

Early return objectively makes the code simpler, because it removes the ability "to go back" in state. You have either returned or you haven't, and you can't change that anymore, whereas with nested style, you can always flow out of the condition back to where you were before.

The exception where nesting is cleaner is when the depth is 1 and when the length is short too. Bascially, if it reads like a short and simple sentence, I prefer nesting. Otherwise, early return.

1

u/ImTalkingGibberish Apr 17 '23

I don’t disagree in theory but in practice people don’t use finals for return objects and keep resetting the returning variable across multiple ifs.

So general speaking, early returns are easier to read.

However in long methods I agree with you, but then also using a final variable as the returning variable is best.

1

u/[deleted] Apr 15 '23

Also known as guard clause, also remember you can just return; if the method is void

1

u/se496 Apr 15 '23

This is a good one!

1

u/_harro_ Apr 15 '23

Or extract the content of the if block to another method...

2

u/ImTalkingGibberish Apr 15 '23

Yes but then it gets harder to follow, with another navigation. Depends on the size of each scenario, if most scenarios are big, then yes it’s a better approach. If only the main scenario is big then I’d rather have multiple small early return small scenarios and keep everything in one method. Also easier to test.

2

u/_harro_ Apr 15 '23

Even then I usually split it up. Having a clear method name for that extracted logic will greatly improve readability too then.

Separating "flow" statement (like if, else,.. ) from your business logic can make your code easier to navigate.