I have the following
class Person
private String firstName;
private String familyName;
// Setters and Getters
And I have the following method
public String getFullName(Optional<Person> persons) {
return persons
.map(person -> (person.getFirstName() + " " + person.getFamilyName())).orElse("Invalid");
}
I just want to check if either first or last name is null, display "Invalid" for that person. I was thinking to add a method for validation but I am sure there is an easier way I cannot think about.
Optionalas a parameter is not a good idea. instead, havingOptional<String>for the method would be better. something like this:Optional<String> getFullName(Person person) { if (person.getFamilyName() == null && person.getFirstName() == null) return Optional.empty(); return Optional.of(person.getFirstName() + " " + person.getFamilyName()); }Optional, being a safe way to return a nullable value. HavingOptionalas a method parameter is kinda violating this principle.