I wrote a Wrapper class for few a strings.
public class StringsWrapper {
private String name;
private String surname;
private String socialSecurity;
public StringsWrapper()
{
name = null;
surname = null;
socialSecurity = null;
}
//getters and setters
...}
There are three scenarios:
socialSecurity = nullleaving name = nullleaving name = null and socialSecurity = nullMy question: would be preferable to use null when an attribute it's not needed or should I use maybe instances of Java 8's Optional?
If you want to point out the fact that some of these are nullable, and the rest of the code makes use of streams/optionals etc., you can make the getters return optionals:
Optional<String> getName() {
return Optional.ofNullable(name);
}
Optional<String> getSurname() ...
etc.
You shouldn't have actual field types as Optionals. One reason being these are not serializable.
But generally the use case you described is probably more suitable for some boolean discriminatory method like isSocialSecurityProvided() that you can later use like this:
if (sw.isSocialSecutiryProvided()) {
// do something with
sw.getSocialSecurity();
} else {
//do domething with
sw.getName();
// and with
sw.getSurname();
}
Even if the whole method looks like something below, one could argue that naming it properly provides better readability of the code:
public boolean isSocialSecurityProvided() {
return socialSecurity != null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With