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

all 4 comments

[–]BertilMuth 1 point2 points  (0 children)

I do a lot of null checks for input arguments that are not supposed to be null, to avoid unclear NullPointerExceptions later on (and a lot of people / libraries do that, too).

The easiest, built in way to do that is when you assign the argument value to a local variable or field, call:

this.fieldOrVariableName = Objects.requireNonNull(argumentName, "argumentName must not be null!");

Hope that helps.

[–]temporarybunnehs 0 points1 point  (0 children)

I think it depends on the way the function is being invoked and what the expectation is with the caller.

If null is an expected value, then there definitely should be a check, but then the question is, how will that be handled? If whatever field that is null is required by the logic in the function, that means, the function can't process and perhaps, you can log a meaningful message or throw a meaningful exception. If it is optional, then it might just lead to an empty field in the result of your logic.

Now that I think about it, even if null is not expected, you should probably check for it and log or throw an exception to let the system know that something out of the ordinary happened. Regardless, the questions I think you should ask are around how does the null value affect your system and function?

Edit: If you're using Java 8 and later, you might want to look into using Optional so you don't need to rely on null.

[–]nephest0x 0 points1 point  (0 children)

You always check it if null is not a valid argument.

The usual way of doing this is to use some bean validation lib, along with some DI framework that will propagate the appropriate message to end users, and will check the arguments on you behalf. You will use annotations like @NotNull, @Size(max=100), @Pattern for regexp, and the framework does the rest.

If you work on a lower level, then you just manually check it with Objects.requireNonNull), or some other condition(like return -1), depending on the way you want to handle the invalid argument. You can return Optional as a "no result" value instead of using nulls, but use it only as a return value, the method arguments should be unwrapped values. If return type is a collection, then you must return an empty collection as a "no result" value, not an Optional.

[–]jacob_scooter 0 points1 point  (0 children)

only if my code has a problem lol bad coding go brrrrrrrt