ND27
ND27

Reputation: 437

Guice inject null check?

I am using google guice inject at the constructor level. Does it make sense to do a null check on the parameters to ensure they are not null or inject does that for us. Btw, its a public constructor.

What about public method?

Upvotes: 1

Views: 2865

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500165

Just because you happen to be using Guice to call the constructor in some cases doesn't mean anything else is prohibited from calling it.

Personally, I would include the nullity checks - which are very light on cruft if you're using Guava as well. For example:

import static com.google.common.base.Preconditions.checkNotNull;

class Player implements SomeInterface {
    private final String name;

    @Inject
    Player(String name) {
        this.name = checkNotNull(name);
    }

    ...
}

Aside from anything else, I'd expect some of your tests to be calling the constructor directly - and it's useful to find any bugs in your tests as early as possible, just like other code. It also expresses your intent clearly to anyone else who comes along later.

Upvotes: 6

Related Questions