-1

I have following code which is supposed to return orgId from modelService but not working with Optional

 public Long getOrgId(String someId) {
    return this.getSpecialOrgId(someId).orElse(this.getById(someId).getOrgId());
}

private Optional<Long> getSpecialOrgId(String someId) {
    return modelService.getModel(someId).map(Model::getOrgId).filter(this::isConditionTrue);
}

This code is not working getSpecialOrgId always returns empty

But following code works well, not sure what's wrong with above code

 private Long getOrgId(String someId) {
     Optional<Long> orgIdFromModel = this.getSpecialOrgId(someId);
     if (orgIdFromModel.isPresent()) {
         return orgIdFromModel.get();
     }
     return this.getById(someId).getOrgId();
 }

 private Optional<Long> getSpecialOrgId(String someId) {
     Optional<Model> modelOptional = modelService.getModel(someId);
     if (modelOptional.isPresent()) {
         Model model = modelOptional.get();
         if (isConditionTrue(model.getOrgId())) {
             return of(model.getOrgId());
         }
     }
     return empty();
 }

where isConditionTrue is always true, This is exact code, I have changed some variable names only

dsk
  • 615
  • 1
  • 7
  • 19
  • I think there is something else happening, the second method does the exact same thing, try with a debugger. – Fabio Filippi Nov 16 '18 at 10:25
  • 1
    If we can’t **reproduce** it, we cannot help.... provide some sample data to prove what your saying is actually the case. – Ousmane D. Nov 16 '18 at 10:27
  • suggestion : You *may* replace `return this.getSpecialOrgId(someId).orElse(this.getById(someId).getOrgId())` with `return this.getSpecialOrgId(someId).orElseGet(() -> this.getById(someId).getOrgId());` – Naman Nov 16 '18 at 10:28
  • Aha! I got it now thanks, It's because of this https://stackoverflow.com/questions/33170109/difference-between-optional-orelse-and-optional-orelseget – dsk Nov 16 '18 at 10:37
  • @dsk you mean you had a side effect in the get? – Fabio Filippi Nov 16 '18 at 10:49
  • `.orElse(this.getById(someId).getOrgId());` was getting called even before `getSpecialOrgId` which used to throw exception. I misunderstood that method, should have used `orElseGet` instead – dsk Nov 16 '18 at 11:07

1 Answers1

1

Looks like you should replace your orElse in getOrgId by orElseGet(() -> getById(someId).getOrgId()).

ETO
  • 6,970
  • 1
  • 20
  • 37