0

I was told that this approach:

public class Example{

private String field

Optional<String> getField(){
   return Optional.of(field);
  }
}

is better than this:

public class Example{
  Optional<String> field;
}

My question is why?

Eduard
  • 11
  • 2
  • 3
    Other than what the title suggests, the difference between the two approaches is not the use of *Optional* but rather whether to use a getter or direct field access. Is this what you are asking? – Codo Feb 10 '22 at 07:54
  • `return Optional.of(field);` makes no sense. you probably meant `return Optional.ofNullable(field);` – Lino Feb 10 '22 at 08:12

0 Answers0