-3

I have a specific code block and I would like to use it more efficiently, shortly using any feautures coming later than Java 8. I do not know if there exists any, so maybe I will continue doing it like before if you do not have any suggestion. This is the code block which I would like to modify:

if(page != null) {
  coPage = companyService.findByCity(city, Integer.valueOf(page)-1);
}else {
  page="1";
  coPage = companyService.findByCity(city, 0);
}

I tried to do it using Optional but I have a problem with the variable "page" because I assign a value to local variable inside the lambda expression which compiler does not allow me to do so.

Naman
  • 27,789
  • 26
  • 218
  • 353
Eric
  • 408
  • 8
  • 22
  • Optional is not designed to replace null checks. It's not. Stop trying to replace null checks by methods of Optional. That's not what it's for. – JB Nizet Aug 03 '19 at 17:23
  • ok, I will keep it in my mind. Thanks.. – Eric Aug 03 '19 at 17:26
  • 3
    I would rewrite that code as `companyPage = companyService.findByCity(city, page == null ? 0 : (Integer.parseInt(page) - 1));` This uses features from Java 1.0. And they still exist in Java 12. – JB Nizet Aug 03 '19 at 17:26
  • 1
    How about `if (page == null) page = "1"; coPage = companyService.findByCity(city, Integer.valueOf(page)-1);`. Also, use `parseInt` instead of `valueOf`. – Andy Turner Aug 03 '19 at 19:11
  • Yes, looks better. Thumbs up. :)= – Eric Aug 04 '19 at 15:11

1 Answers1

0

This is quite simple to do with Optional:

coPage = companyService.findByCity(city, Integer.METHOD(Optional.ofNullable(page).orElse("1"))-1);

where METHOD is one of parseInt and valueOf respectively.

However, it's generally better to use Optional in the following manner, as specified by Brian Goetz

[Optional is] a limited mechanism for library method return types where there [needs] to be a clear way to represent "no result", and using null for such [is] overwhelmingly likely to cause errors.

Avi
  • 2,611
  • 1
  • 14
  • 26