Optional is probably not going to help you here.
The first thing to think of, is sentinel values. Here you are clearly indicating that you think that, semantically, reg[0]
being null is equivalent to reg[0]
being the empty string (or even a string with only spaces in it). That is supposed to be extraordinary. null
is not a standin for 'nothing' or 'empty'. null is supposed to be a standin for 'There is no value'. The best way to do this, is to find the place that generates reg[0]
, and ensure that the proper semantic meaning (an empty string) is set up here. Then this code can simply be: if (!reg[0].isEmpty()) orderData.setCity(reg[0]);
- so much cleaner.
That is, of course, not always possible. For example, if reg
is coming down the pipe from a library or other code that simply isn't under your control, or it is an object created by, say, a JSON demarshaller.
In that case I generally would advise creating an explicit step to convert an object that is 'not clean' (has nulls even when semantically that's supposed to be an empty string) into a clean one.
If that is not feasible or not possible, well, working with an 'unclean' object is never going to be particularly pretty, style wise. A helper method would help a lot, here:
normalizeThenSetIfNonBlank(reg[0], orderData::setCity);
normalizeThenSetIfNonBlank(reg[1], orderData::setCountry);
private void normalizeThenSetIfNonBlank(String in, Consumer<String> target) {
if (in == null) return;
in = in.trim();
if (in.isEmpty()) return;
target.accept(in);
}