I am new to java, was using php, python and js before. Lately python, so get used to something like "if myVar is None:". Here is my problem: I am getting locale from some library as Optional, I need to return a language only, or something else if timeout happened, or some errors, etc. Then I need to pass language to some object (context), and somewhere later convert context to request's parameters. So I do something like
String getLanguage(){
try {
Optional<String> locale = getLocale();
if (locale.isPresent()){logging, locale.get()-to-language conversion, language validation,
logging, return language}
else (logging, return null;)
} except {logging error, return null};
}
Context c = new Context();
c.setSomething(something);
c.setLanguage(getLanguage());
and somewhere later:
Request r = new Request();
r.addParam(something, c.getSomething());
if (c.getLanguage() != null) {r.addParam(language, c.getLanguage())
I have got a suggestion to rewrite everything using Optional. Replace my first method with something like.
Optional<String> getLanguage(){
try {
Optional<String> locale = getLocale();
return locale.ifPresent(logging)
.map(locale-to-language conversion, language validation, logging, return language}
.orElse(logging, return Optional.isEmpty())
} except {logging error, return Optional.isEmpty()};
}
and then somewhere later c.getLanguage().ifPresent(x -> r.addParam(language, x))
I never used Optional before, so I am happy to learn something new, and I assume for person who get used to Optional my code is not good. From other side I see that Optional here is overkill here - I need to modify my data class Context to deal with Optional, my map() and orElse() are ugly - they have 2-5 lines of code, etc. also unit tests need rework. So, my question is - are those changes to Optional adding some benefits or we are just following fashion without thinking.