Search code examples
javareturnjxbrowser

"Unexpected Return Value" in Method that uses List<Element>


I want to start by noting that I'm quite new to coding, so this might seem quite simple, but I just can't figure it out.

I am working with an existing project that uses JXBrowser to extract information from a website. It selects all the elements with the method getRecords() from the website objects and puts it into a List<Element> (part of import java.util.List). This piece of code is a method inside the Browser Manager Class, which creates and handles the JXBrowser instance.

I want the saveRecords() method to pull the data from the website and return the List to my main Job Executor. However, my IDE marks the return records part as wrong - "Unexpected return value".

I suspect it might have something to do with using the anonymous method, which I didn't write myself and don't have any experience with.

   public List<Element> saveRecord() {

    if (website != null) {

        browser.mainFrame().ifPresent(frame -> frame.document().ifPresent(document -> {

            List <Element> records = website.getHandler().getRecords(document);

            if (records.isEmpty()) {
                log.error("no record found on site!");
            } else {
                return records;
            }

        }));
    } else {
        log.error("no handler found!");
    }
}

Solution

  • You're not returning anything from your method, which should return a List<Element>. And on the other hand, you're returning (but not in all cases) from the function (lambda) passed to Optional.ifPresent(), although the lambda is supposed to be a Consumer, and thus shouldn't return anything.

    If you don't understand the principle of functions (lambdas) passed as callbacks to methods, I would suggest studying that before using them. Or to stay with imperative programming by simply using Optional.isPresent() followed by Optional.get() to test if the optional has a value and getting it if it's present.

    If you want to use functional programming, then you shouldn't use ifPresent(). You should instead use map(), flatMap() and orElse to transform your Optional into a value.

    In all cases, the first thing you need to decide is what to do if records is empty, and what to do if website is null. You can't just not do anything as you're trying to do. Either you return something (an empty list for example), or you throw an exception. But you can't just log an not return.