Search code examples
javanulloption-type

Passing null to methods with Optional as parameters


CONTROLLER CLASS
@PostMapping("Calculate")
    public String Calculate(@ModelAttribute("currencyAndAmount") @Valid CurrencyViewModel currencyViewModel,
                            BindingResult bindingResult, Model model) {
        if (!bindingResult.hasErrors()) {
            var entity = currencyExchange_logic.CurrencyViewModelToEntity(currencyViewModel);
            String start = Optional.ofNullable(entity.getDateFrom().toString()).orElse("");
            String end = Optional.ofNullable(entity.getDateTo().toString()).orElse("");
            try {
                var currencyJson = currencyExchange_logic.currencyJson(start, end);
                var calVal = currencyExchange_logic.calculateMoney(currencyJson, entity);
                model.addAttribute("endValue", calVal);
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
            return "end";
        } else {
            return "formPage";
        }
    }

SERVICE CLASS

@Override
    public MonetaryAmountJson currencyJson(String start, String end) throws IOException {
        String dates = "/" + start + "/" + end;
        URL url = new URL("http://api.nbp.pl/api/exchangerates/tables/c" + dates);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder jsonObject = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            jsonObject.append(line);
        }
        bufferedReader.close();
        Gson gson = new Gson();
        return gson.fromJson(String.valueOf(jsonObject), MonetaryAmountJson.class);
    }

The question that I have is that in the line:

var currencyJson = currencyExchange_logic.currencyJson(start, end);

So in a frontend form there are 2 date inputs that can be left empty (not filled by user) and I want to pass to currencyJson() method Optional.of(given date (maybe null).toString()) the logic within it i.e. Optional.ofNullable(null).orElse(""); won't return "" (empty String). Am I passing "" or null to currencyJson()?


Solution

  • If the entity.getDateFrom() is actually null, Optional.ofNullable(entity.getDateFrom().toString()) should throw a NullPointerException, because toString will be called on null before Optional.ofNullable is called.

    But your question doesn't state that you get a NullPointerException in your original code, so think that the date values are not null, but rather some default value.

    Now, if the default values are actually null, and if you want to continue using Optional you could do this instead:

    String start = Optional.ofNullable(entity.getDateFrom())
                           .map(Object::toString)
                           .orElse("")
    String end = Optional.ofNullable(entity.getDateTo())
                           .map(Object::toString)
                           .orElse("");
    

    ...or (easier):

    String start = Objects.toString(entity.getDateFrom(), "")
    String end = Objects.toString(entity.getDateTo(), "")