DEV Community

Discussion on: Make an Immutable Object - in Java

Collapse
 
moandip profile image
Sir Mo

If I remember correctly having optionals as fields is an antipattern or at least not really good practice. However I don't recall why.

What's the advantage in contrast to simply wrapping the object in the getter:


public Optional<int> getWeight() {
return Optional.ofNullable(weight);
}

?

Besides my question. Great article dude!

Collapse
 
monknomo profile image
Gunnar Gissel

Thanks for reading!

What I've read is that people advise against taking Optional as an argument (this is a pretty fair example of the argument). I disagree with that, or at least I weight my considerations differently.

I think taking Optional as an argument clearly signals to the user of the class what the implementer of the class is expecting in terms of required fields. I feel that being clear to the users of the code is generally more important than being kind to the compiler or performance, but all of this is subject to the actual use case.

My unstated assumption is that everything is setup to fail immediately if a null is passed around. For example:

public static void doSomething(String arg1, Optional<String> arg2){
  Objects.requireNonNull(arg1);
  Objects.requireNonNull(arg2);
  if(arg2.isPresent()){
    //do whatever
  } else {
    //handle the absent value
  }
}

vs.

public static void doSomething(String arg1, String arg2){
  Objects.requireNonNull(arg1);
  if(null == arg2){
    //handle the absent value
  } else {
    //do whatever
  }
}   

To me, that seems better than the normal null checking dance we Java programmers go through.

How does it compare to wrapping the object getter? I've tried it that way, and in terms of using the class it's fine. My biggest complaint is you can't just code gen the getters if you do that. I also taking Optional as an argument clarifies code enough to outweigh the disadvantages in most situations.

I guess I should also say that all this Optional stuff is in context to the immutable object. I'm a little on the fence with Optional in the builder, not sure how I feel one way or another.

Collapse
 
monknomo profile image
Gunnar Gissel
Thread Thread
 
moandip profile image
Sir Mo

Thanks for the explanation. In general I agree at least with your readability over performance thingy.

I'd still go for the getter way tho. However I agree that using an optional as argument can be ok. I would still prefer doing something like throwing an illegal argument exception because npes are kinda ugly. Also to remove that if else clutter you could wrap the arg2 in an optional and map or else.

However that is not really related to immutability. I liked the article :)