Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I avoid returning null in my java function? [closed]

Tags:

java

null

I don't find the appropriate solution for my question. As far as I know returning null is a not a good way to write clean code, as the book Clean Code says. However there are many different opinions about this practice, and I am not sure about which one fits on my function.

private EArea getSimilarExistingArea(EImportArea importedArea) {
    for (EArea existingArea : exsitingAreas) {
        EList<EPoint> importedAreaPoints = importedArea.getPoly().getPoints();
        EList<EPoint> existingAreaPoints = existingArea.getPoly().getPoints();
        for (EPoint importedAreaPoint : importedAreaPoints) {
            for (EPoint existingAreaPoint : existingAreaPoints) {
                if (importedAreaPoint.equals(existingAreaPoint))
                    return existingArea;
            }
        }
    }
    return null;
}

What should I return if there is not an existing similar area?

PD: For optimize my code I am breaking the loops with the return if an existing area is founded.

like image 338
Alex Blasco Avatar asked Oct 18 '25 09:10

Alex Blasco


1 Answers

You should take a look at the Optional class!

Make your method return type Optional<EArea> and simply return Optional.ofNullable(existingArea) you will have to slightly modify your Code but the benefits of Optional are really worth it!

like image 141
Dinh Avatar answered Oct 20 '25 22:10

Dinh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!