简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM