Torben
Torben

Reputation: 31

Java return must not be null

I have the following code:

public abstract class Task<S extends AbstractScript>
    public S getScript() {
        return (S) Environment.getScript();
    }
}

Environment.getScript() returns the current AbstractScript

However, this AbstractScript might be null, but the S (which is an AbstractScript) returned at getScript() must not be null because it is used many times, therefore I don't want to null check it all the time.

I thought of null checking Environment.getScript(), but in the case of null I don't know what to return then.

Upvotes: 2

Views: 75

Answers (1)

Bohemian
Bohemian

Reputation: 424993

If it can't be null, but you don't know what to return instead, either:

Have the concrete implementation specify what its default should be:

public abstract class Task<S extends AbstractScript> {
    private final S deflt;
    protected Task(S deflt) {
        this.deflt = deflt;
    }

    public S getScript() {
        S s = (S)Environment.getScript();
        return s == null ? deflt : s;
    }
}

Or make the caller specify it:

public S getScript(S deflt) {
    S s = (S)Environment.getScript();
    return s == null ? deflt : s;
}

Upvotes: 1

Related Questions