0

Is it good to write like this?

UserInfo myMethod(User user) {
    user = Optional.ofNullable(user).orElse(new User())?

    String name = user.getName()
    String type = user.getType();

    return new UserInfo(name, type);
}

Or better use standard way:

UserInfo myMethod(User user) {
    if(user == null) { return null }
    
    String name = user.getName()
    String type = user.getType();

    return new UserInfo(name, type);
}

Could also someone help with good null safety best practice links?

Alexander.Iljushkin
  • 4,519
  • 7
  • 29
  • 46
  • 2
    It depends on why `user` is allowed to be null in the first place. – Karl Knechtel Jul 07 '21 at 06:17
  • 1
    One important part of handling `null` is to **define** what happens when you pass `null` to it. A straightforward one is to straight up forbidd it (and throw an exception if it happens anyway). And as long as your project has a good general guideline in this regard (for example "null values are not allowed as parameters except in exceptionas A, B and C and those need to be indicated using X, Y and Z" you don't even always need to read that documentation to know how `null` is handled. – Joachim Sauer Jul 07 '21 at 06:22
  • You could make a new constructor for UserInfo that takes a User object, which might be null. – NomadMaker Jul 07 '21 at 06:46

1 Answers1

2

The first version looks pretty much a code smell: you return a UserInfo object corresponding to a null User. This seems like a counter-intuitive approach, and can lead to all sorts of validation problems if the fields name and type are unspecified. The second version is better because it just returns null if the user is null. Another approach is to enforce the caller to pass a non-null argument using:

UserInfo myMethod(User user) {
    Objects.requireNonNull(user);
    ...
}
M A
  • 71,713
  • 13
  • 134
  • 174