I recently found out about the Optional type in java 8 and started using it in my latest project. I used it like:
public class User{
private int id;
private String email;
private Optional<String> mobile;
public User(int id, String email, Optional<String> mobile){
...
}
public int id(){...}
public int email(){...}
public Optional<String> mobile(){...}
}
Today i was exploring more about Optional when i came across posts which clearly stated that using Optional at places other than return type is a bad practice. After verifying this from multiple sources i changed my code like:
public class User{
private int id;
private String email;
private String mobile;
public User(int id, String email, String mobile){
...
}
public int id(){...}
public int email(){...}
public Optional<String> mobile(){
return Optional.ofNullable(mobile);
}
}
Is this an accepatable solution? Specifically i changed some method signatures taking in Optional to T and then inside the method I converted T to Optional.ofNullable(t) so that i can use methods like ifPresent, orElse, filter, map etc.