If i need a value from deep nested object structure where every next reference might be null, i line using optional to retrieve it instead of multiple null checks.
Next next = Optional.ofNullable(ref).map(MyRef::getNext).map(Next::getNext).map(Next::getNext).orElse(null);
Your classes have only strings and primitive fields? i imagine having data structures limited to only classes with primitive fields. i see 10000 maps trying to make simple relation between objects becauses classes are limited to have no nesting and cant be used for complex data structures anymore.
i parsed an xml document some days ago into a java model. the java class model was according to the xml model. so i got a reference to the root object and made chained calls to the relevant object. dont see any smell here
No, of course that's just accessing some specific external data on the boundaries of your program. I was talking more about general modeling. For example, if you had modeled the object that is represented by that XML, you probably wouldn't be acessing that element directly but rather deserializing it into a real world object that interacts with the rest of your model in some other way.
Please don't do this. Optional is not a replacement for an if-statement. Imo Optional should only be used if immediately returning.its fine to add mapping expressions like this, but only if you're actually returning an optional of the mapped type.
It's not different than wrapping some function you don't control such that that function now returns an optional. If you had such a function that returned an optional, you would use it just like /u/devchonkaa suggested.
WTF? That is awful and is an abuse of Optional. It has no advantage over an if-statement. You are also creating a lot of short lived objects the GC has to deal with (especially if you do that in a loop).
To anyone who's opposed to this approach: maybe you are lucky to have good structured entities and don't see the benefits of this approach.
I have to deal with some pretty nasty legacy crap, and this is absolutely better then having deeply nested ifs.
Say you have a maybe nullanle cistomer and want to .getAddress().getZipCode().getNumber(). Mind you this is a pretty shallow example, and oftentimes the field names are in the good old enterprise style of being 20 chars long, those ifs get pretty unreadable pretty fast.
9
u/[deleted] Apr 14 '23 edited Apr 14 '23
If i need a value from deep nested object structure where every next reference might be null, i line using optional to retrieve it instead of multiple null checks.
Next next = Optional.ofNullable(ref).map(MyRef::getNext).map(Next::getNext).map(Next::getNext).orElse(null);
if (next == null) return;