I think I learned something here again, because thanks to the wonderful comments by Olivier Grigorey, Louis Wassermann, Collind and Captain Man. Standards are usually a strong and sufficient reason, since they do that ordinary programmers will always understand correctly, but in this particular case I had little doubt that perhaps this rule, established around NPE, is not too good. Java is an old language, and some of its functions turned out to be a bit unsuccessful (I don’t want to speak incorrectly, it may be too strong a judgment) - for example, checked exceptions , although you may also disagree. Now I think this doubt is resolved, and I should:
- Throw an IllegalArgumentException when, in a specific context, I can say why a null value is wrong, and not from a business perspective. For example, in the service method
public void call(Person person) I know what it means that the system has a phone number. - Throw a NullPointerException when I just know that a null value is wrong here and sooner or later will throw a NullPointerException, but in the specific context, I don't know what this means from a business perspective. An example is the immutable collections of Guavas. When you build one and try to add a null value element, it throws you an NPE. He does not understand what this value means to you, it is too general, but he simply knows that it is wrong, so he decides to report it immediately, with a more appropriate message, so that you can more efficiently recognize the problem.
Keeping in mind, I would say that the best option, so that the statement in the public void call(Person person) example would look like Captain Man, suggests:
Preconditions.checkArgument(person.getPhone() != null, "msg");
Checking an argument is a good name for this method - it’s clear that I am checking whether the business contract matches the argument to person, and it’s clear that I am expecting an IllegalArgumentException if it does not. This is a better name than Validate.isTrue from Apache Commons. On the other hand, saying Validate.notNull or Preconditions.checkNotNull suggests that I check for a null reference and I really expect NPE.
Thus, the final answer will be: there is no such beautiful library and should not be the way it would be confused. (And Spring Assembler should be fixed).
source share