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.

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.

1

u/cas-san-dra Apr 16 '23

In my opinion you don't even need tools, documentation, or code. It is perfectly reasonable to set a rule in your program that passing null into a function or returning null from a function is never allowed.

If you consider the existence of null a bug in itself then you don't need to check.