-2

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.

  • Use whatever you think reads best in the specific context. – Louis Wasserman Feb 08 '20 at 02:37
  • ...adding to that, just try to move things like `map(locale-to-language conversion, language validation, logging, return language}` to a method of their own. – Naman Feb 08 '20 at 02:39
  • This code does not compile even. Please provide a minimal and reproducible example first: https://stackoverflow.com/help/minimal-reproducible-example – Ravindra Ranwala Feb 08 '20 at 02:49
  • @Naman, already did. Those "locale-to-language conversion" and "language validation" are already methods, also my logging is using some other local variables, so if I am moving those things to a new method, I need 3 extra parameters just for logging. Methods don't look good. – user7497021 Feb 08 '20 at 02:54
  • @RavindraRanwala this is a pseudo code to represent the idea, not a real code. – user7497021 Feb 08 '20 at 02:56
  • I recently jesitatingly gave up returning an `Optional` in a similar situation. In my work we are still using Java 8. If Java 9 and its `Optional.ifPresentOrElse()` had been available to me, I would no doubt have returned `Optional`. – Ole V.V. Feb 08 '20 at 20:41

2 Answers2

2

So, my question is - are those changes to Optional adding some benefits ...

Well there are definitely advantages and disadvantages for both approaches:

Looking from the Optional side, the main "plus" is that you eliminate a major source of bugs; i.e. NPE's caused by not dealing with a possible returned null correctly. The main "minuses" are the verbosity of code that uses Optional, and that it doesn't actually eliminate all bugs; e.g. if you call Optional.get on an "empty" Optional you will get an exception.

Other Q&A's go into more detail:

... or we are just following fashion without thinking.

That is a different question!

Now I imagine some people may be using Optional without thinking, but I don't see much evidence of that. It is clear that there are advantages AND disadvantages, and that thought is required.

So you should really be asking (yourself!) if >>you<< just following fashion without thinking? Or to put it another way, are you just treating this as a (so-called) "best practice", or are you making a reasoned choice between the two approaches depending on the context?


I have got a suggestion to rewrite everything [in my example] using Optional.

Here's what I suggest.

  1. Create a branch in your version control system.
  2. In the branch, change your API method to use Optional, and change all of the places in your code that use the API method.
  3. Make a judgement: has this improved things? was the effort worth it?
  4. If the API is currently or going to used by other people's code, ask their opinions too.
  5. Decide whether to proceed or not, implement decision, and move on to the next issue.

If that sounds like too much work, another option is to quietly ignore that suggestion.

Either way, we (the StackOverflow community) can't decide for you. We don't have the context1, and even if we did, there would be a range of opinions and no clear correct answer.


1 - For instance, what is the likelihood of there being no locale, and no determinable language. What the application as a whole should do about it? Should it bail out? Should it substitute a default? Could the default be substituted ... here? We can't see "the big picture".

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • While overall this is a good answer, I disagree with `the main "plus" is that you eliminate a major source of bugs; i.e. NPE's` If you fail to check an `Optional` properly, it throws `NoSuchElementException`. This is not an improvement over NPE. I'd call that "fake functionality" myself. – markspace Feb 08 '20 at 05:55
  • Updated. Better? – Stephen C Feb 08 '20 at 06:06
  • I think your explanation is clear, but I'm not sure that's the reason. The idea goes something like if you pass that returned `null` to another method or class, and *that* class throws NPE, the NPE doesn't actually point to the code that caused the problem. `Optional` is supposed to change that by forcing the receiver to test. But I still don't feel that has enough value to make the extra complexity worth it. – markspace Feb 08 '20 at 06:11
  • It is a matter of opinion. I am not passing judgment on the opinion, one way or another. If you think this is important, then you should write your own answer. – Stephen C Feb 08 '20 at 06:18
0

I would say Optional is good when your code knows how to deal with the null situation. For example you can write

 public String helloWorld(Optional<Long> input){
     String toReturn = "Hello "+ input.orElse("0")+ " times";
     return toReturn;
 }

However, if you are interfacing with legacy code and those functions expect null inputs, which force you to write something like

if(someOptional.isPresent()){
       return somevalue;
} else{
       return null;
 }

In the above case, Optional does not bring you more than using null only. In this case I would use null over Optional.

HarryQ
  • 1,281
  • 2
  • 10
  • 25