This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.
For JDK 7 users, Here using
Objects.requireNotNull(object[, optionalMessage]);
is not safe. This function throws NullPointerException
if it finds null
object and which is a RunTimeException
.
That will terminate the whole program!!. So better check null
using ==
or !=
.
Also, use List
instead of Array
. Although access speed is same, yet using Collections
over Array
has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector
without rewriting all your code.
public static double calculateInventoryTotal(List<Book> books) {
if (books == null || books.isEmpty()) {
return 0;
}
double total = 0;
for (Book book : books) {
if (book != null) {
total += book.getPrice();
}
}
return total;
}
Also, I would like to upvote @1ac0 answer.
We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.
Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException
. It defined a new class called Optional
. Have a look at this for detail
Finally, Pardon my bad English.