Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use Java 8's Optional in my wrapper class or null when not using some attributes?

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:

  • I will set only name and surname, leaving socialSecurity = null
  • I will set only surname and socialSecurity, leaving name = null
  • I will set only surname, leaving name = null and socialSecurity = null

My 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?

like image 336
zaxunobi Avatar asked Jul 28 '26 04:07

zaxunobi


1 Answers

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;
}
like image 91
pafau k. Avatar answered Jul 30 '26 19:07

pafau k.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!