Which @NotNull Java annotation should I use?

前端 未结 22 2806
梦如初夏
梦如初夏 2020-11-22 02:44

I\'m looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.

22条回答
  •  悲&欢浪女
    2020-11-22 03:29

    There is another way to do this in Java 8. I am doing 2 things to accomplish what I needed:

    1. Making nullable fields explicit with types by wrapping nullable fields with java.util.Optional
    2. Checking that all non nullable fields are not null at construction time with java.util.Objects.requireNonNull

    Example:

    Edit: Disregard this 1st example, I'm just leaving here as context of the comments conversation. Skip to recommended option after this (2nd code block).

        import static java.util.Objects.requireNonNull;
    
        public class Role {
    
          private final UUID guid;
          private final String domain;
          private final String name;
          private final Optional description;
    
          public Role(UUID guid, String domain, String name, Optional description) {
            this.guid = requireNonNull(guid);
            this.domain = requireNonNull(domain);
            this.name = requireNonNull(name);
            this.description = requireNonNull(description);
          }
    

    So my question is, do we even need to annotate when using java 8?

    Edit: I found out later that some consider a bad practice to use Optional in arguments, there is a good discussion with pros and cons here Why should Java 8's Optional not be used in arguments

    Recommended option given that it is not best practice to use Optional in arguments, we need 2 constructors:

      //Non null description
      public Role(UUID guid, String domain, String name, String description) {
            this.guid = requireNonNull(guid);
            this.domain = requireNonNull(domain);
            this.name = requireNonNull(name);
    
            // description will never be null
            requireNonNull(description);
    
            // but wrapped with an Optional
            this.description = Optional.of(description);
          }
    
      // Null description is assigned to Optional.empty
      public Role(UUID guid, String domain, String name) {
            this.guid = requireNonNull(guid);
            this.domain = requireNonNull(domain);
            this.name = requireNonNull(name);
            this.description = Optional.empty();
          }
    

提交回复
热议问题