JF Meier JF Meier - 1 year ago 48
Java Question

What to do in findXY method if no such object exists?

Assume I have a Java method

public X findX(...)

which tries to find an Object of type
fulfilling some conditions (given in the parameters). Often such functions cannot guarantee to find such an object. I can think of different ways to deal with this:

  1. One could write an
    public boolean existsX(...)
    method with the same signature which should be called first. This avoids any kind of exceptions and null handling, but probably you get some duplicate logic.

  2. One could just return null (and explain this in javadoc). The caller has to handle it.

  3. One could throw a checked exception (which one would fit for this?).

What would you suggest?

Answer Source

The new Java 8 Optional class was made for this purpose.

If the object exists then you return Optional.of(x) where x is the object, if it doesn't then return Optional.empty(). You can check if an Optional has an object present by using the isPresent() method and you can get the object using get().