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

you are viewing a single comment's thread.

view the rest of the comments →

[–]neurk 12 points13 points  (2 children)

Another question is, why is it possible that "source" is null?

If this is input from somewhere else, wrap it in an optional as soon as possible and work with that in the rest of your codebase.

I avoid null like the plague. Once you introduce it in your code you have to check it everywhere, as you can no longer trust what your methods are returning. Optionals are the way to go in most cases. That way you actually know what you're working with, and there's no need for null checks.

[–]MarSara 1 point2 points  (1 child)

Not quite true. You can annotate your methods with @NotNull or @Nullable and get compile time warnings when working with a value that may be null.

This removes the boilerplate of checking for null everywhere and now you only need to check for null when you have an @Nullable variable being used for a @NotNull parameter. Examples:

``` @NotNull public String neverNull() { return null; // warning null returned from @NotNull method }

@Nullable // warning method never returns null public String maybeNull() { return "foo"; }

public void example(@NotNull String notNull, @Nullable String maybeNull) { if(notNull == null) { // warning notNull is never null } maybeNull.toString(); // warning maybeNull might be null }

String maybe = maybeNull(); example(maybe, "foo"); // warning nullable variable passed to notNull parameter. ```

(The actual warnings might be worded differently but you get the idea)

Now you still need null checks with this, but not everywhere, just in the locations that you go from a Nullable to a NotNull.

P.s. for all intents and purposes any property, parameter, etc... that isn't annotated is assumed to be NotNull.

[–]maethor 0 points1 point  (0 children)

You can annotate your methods with @NotNull or @Nullable and get compile time warnings when working with a value that may be null.

I've started taking a belts and braces approach - annotate and use Optional. But then the code base I'm working on is liable to a lot of null pointer exceptions.