Methods

Java Best Practices Series

Methods

49. Assert Method Arguments Validity

Whenever an object is given in as a method argument, it should be asserted in terms of validity as the first thing.

This can be done with something as Objects.requireNonNull(arg), which will throw an exception if the argument is null.

Additionally, if you want to determine which arguments, should be allowed to be nullable, the @Nullable annotation can be used.

50. Using Defensive Copies

Some objects are mutable and can therefore be changed at any time. If you provide a mutable object as a field to an immutable object, it will create a problem. Since the mutable object can be altered after being assigned to the field it thereby makes the immutable object into a mutable object.

To avoid this situation, it is required to make defensive copies of the mutable object when they are being assigned to the immutable objects field.

this.start = new Date(start.getTime());

51. Design Clean Method Signature

Every method should pull its own weight, be concise, and self-explanatory.

Making methods with three or more arguments, should be reconsidered and perhaps changed and divided.

Similarly providing bad or incorrect names for both method and arguments can be confusing and can potentially lead to mistakes.

52. Overloading Methods Are Rarely Needed.

Overloading methods generally creates more confusion then it helps. Except for constructors, it is always possible to make a different method name, which enlightens how the two methods differ from each other.

If a method has to be overloaded it should arguably be because of variations in the number of arguments for the methods.

Otherwise, if the argument number stays the same, it might be worth considering renaming the methods or using a different design pattern.

53. Be Cautious When Using Varargs

Varargs work by making an array with the same size as the number of arguments. However, this number can be anything from zero and up.

This often creates the issue that developers attempt to handle the zero-argument scenario by throwing an exception. This is bad practice, since future developers might not be aware of this functionality and call the method assuming that zero varargs have been handled.

An appropriate way of handling this, is to request the initial argument, which would otherwise have been the first one of the varargs.

Additionally, it is worth noting that varargs are generally bad in terms of performance. It might therefore be worth considering alternatives, if you know the number of arguments are limited to a certain range. (e.g. 1-3)

54. Return Empty Arrays And Collections, Never Null

Returning null should always be seen as a ticking bomb in the receiving system. Therefore, if you are intending to return an array or collection of some sort, it is always better to return an empty version of the array or collection.

return Collections.emptyList();

return collection.toArray(new ArrayClass[0]);

55. Working With Optionals

Similar to item 54, the same can be achieved for single objects by using Optionals.

Wrapping return value in Optionals, forces the receiving system to handle the same scenarios.

However, having an Optional does not mean that you can simply pass it around the system. Any optional should be unwrapped as soon as possible after they are returned from the API.

That means DTOs should never take Optionals as input. Additionally, this is supported by the fact that Optionals are not serializable.

However, if you are unsure of whether or not an object intended for the DTO is present, you can set it in the as a @Nullable object in the constructor. Whenever you then want to return the object, it can simply be wrapped in an optional.

56. Write API Documentation

Every exposed API method, should ideally have a well described Javadoc.

Using tags can be a useful way to describe what the method is doing and what the user should be aware of when using it.

Recommended Reading

Article

  • Java Optional in class fields – Marcin Piczkowski – Blog

Books

About

Hi, I'm the Author

My name is Daniel H. Jacobsen and I’m a dedicated and highly motivated software developer with a masters engineering degree within the field of ICT. 

I have through many years of constantly learning and adapting to new challenges, gained a well-rounded understanding of what it takes to stay up to date with new technologies, tools and utilities. 

The purpose of this blog is to share both my learnings and knowledge with other likeminded developers as well as illustrating how these topics can be taught in a different and alternative manner.

If you like the idea of that, I would encourage you to sign up for the newsletter.

Cheers! 🍺

Didn't Find What You Were Looking For?

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
Scroll to Top