3

I have a class where I have injected a field using javax.inject.Inject annotation

import javax.inject.Inject;

public class Foo extends BaseFoo {
  @Inject
  private Bar bar;
  ...

  public void execute(){
    if (bar == null) {
      //log failure message and return
      return;
    }
    //Do your work..
  }
  ...
}

My question is whether in the above example, is null check needed or not? and why?

Learner
  • 1,503
  • 6
  • 23
  • 44
  • I'm not sure. I'd use an injectable constructor to a final field. – Michael Mar 08 '17 at 15:19
  • Thanks for the accept. Let me know if there is anything I could do to make my answer upvote worth in your eyes, like adding other information... – GhostCat Apr 08 '17 at 04:21

1 Answers1

0

The answer is: it depends.

If you think there are valid scenarios, where the injection process will not inject null, then you do need that check. If you think that should never happen, then you probably end up with a NPE at runtime; and then again; you have to figure for yourself if that behavior is "appropriate" in your context (and what/how to deal with it then).

But I would rather strive to make that field final and put the annotation on your constructor; and then you can just put a Objects.requireNonNull() check on the incoming argument; and you are later on sure that any Foo object of are null free.

GhostCat
  • 137,827
  • 25
  • 176
  • 248