I am trying with Optionals and I am pretty sure my solution is not good. I put a little sample below.
class Person {
String name; // can be null
Integer age; // can be null
}
class DB {
// returns an Optional
public static Optional<Person> getPerson() {
//irrelevant code here
}
}
public static void main() {
Person p = DB.getPerson().orElse(null);
// did I get a Person?
if (p != null) {
// both information of a Person available?
if (p.name != null && p.age != null) {
dosomthing (p.name, p.age);
}
}
}
Any idea how to improve this? I see HERE no benefit in using Optionals. But I am not in charge of getPerson.
getPerson()without the orElse, you'll receive anOptional<Person>. Then you can check things likep.isPresent()instead ofp != null. Although the example feels a little contrivedPerson'snameandagecannot benull, can't you just make them non-nullable? If that's not possible, you could havedosomthingdo the checks before running any operation.getPersonshould return an empty optional in such cases.