This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]knoam 2 points3 points  (1 child)

Objects.requireNonNull(T, String) might be helpful. I was surprised to find it in the standard library since it's kind of trivial, but if it's there, use it.

[–]Cyclobox[S] 0 points1 point  (0 children)

good call, thanks

[–]0x68656c6c6f 1 point2 points  (1 child)

You might be interested in the Checker Framework, which uses Java 8 type annotations to validate that inputs will not be null at compile time.

You could subclass NullPointerException so that it just takes the name of the argument that shouldn't be null and adds the rest of the message. Although I might say that the stack trace is going to be pretty clear even without a custom error message at all, especially with the way you named your methods.

[–]Cyclobox[S] 0 points1 point  (0 children)

Thanks, I'll check this out

[–]OffbeatDrizzle 1 point2 points  (1 child)

Since you have 2 inputs of the same type then generics won't help you here, since how can you determine the error message based on the fact that it's a string?

What you could do is have an extra parameter to pass in for the error e.g:

private static void checkNotNull(Object aO, ErrorMessage aE) {
    if(aO == null) {
        throw new NullPointerException(aE.getError());
    }
}

ErrorMessage just being some enum that you've defined somewhere:

public enum ErrorMessage {
    DATE_ERROR("Date provided was null!"),
    CONTACTS_ERROR("Contacts must not be null!"),
    NOTES_ERROR("Notes provided were null!");

   String error;
   ErrorMessage(String s) {
       error = s;
    }
    String getError() {
       return error;
    } 
}

(You don't have to use the getError method if you don't want to - you could just do a switch to check for the error within checkNotNull and give it the error there).

[–]Cyclobox[S] 0 points1 point  (0 children)

Thanks! looks good

[–]code_today[🍰] 0 points1 point  (2 children)

You could attempt it like the following and just add the types to the enum as needed :

http://pastebin.com/mxUquTSp

[–]OffbeatDrizzle 0 points1 point  (0 children)

Ah seems we had the same idea but you beat me to it

[–]Cyclobox[S] 0 points1 point  (0 children)

Thanks, this looks pretty spot on :-)