1

I am wondering if I can get some advice regarding the use of Java 8's Optional class to wrap nullable columns in entities. What I mean is expressed in the following code example:

@Entity
public class Data {

    @Column(nullable=true)
    private String value;

    public Optional<String> getValue() {
        return Optional.ofNullable(value);
    }

    public void setValue(Optional<String> value) {
        this.value = value.orElse(null);
    }

The column in the database can still be made null, however, in order to check for null, one must call the getter with the isPresent() method. I like the explicitness, opposed to having to check or remember if a column is nullable. Is such a pattern common and/or recommended? If not, can you provide a good reason why I shouldn't do this?

mrks_
  • 359
  • 4
  • 20

1 Answers1

2

Brian Goetz himself answered this question. His verdict:

I think routinely using it as a return value for getters would definitely be over-use.

Basically, Optional wasn't designed to be a general purpose Maybe or Some type. There are some things it should definitely not be used for, getters are okay but don't go nuts.

Community
  • 1
  • 1
sh0rug0ru
  • 1,596
  • 9
  • 9