How can I get rid of excessive null checking in java?

design-patterns, java

Solution

It sounds like basically you want your repository to support this:

Vehicle vehicle = vehicleRepository.loadExisting(vehicleId);

where the difference between `loadExisting` and `findByIdInitialized` would be that the former expects the entity to be present and will throw an a exception if it's not.

That way all repository clients can make a decision as to whether when they perform a lookup, they want the lack of an entity to result in an exception or not. You may even find that all lookups by ID should throw an exception - in which case you can go back to having a single method.

EDIT: If the repository is autogenerated, I'd take one of three approaches:

- Wrap it

- Extend it

- Modify the generator

Which of these choices would be most appropriate would depend on the exact details.

Problem

Suppose I have some code like this: ``` Vehicle vehicle = vehicleRepostory.findByIdInitialized(vehicleId); ``` If the `Vehicle` cannot be found this method will return `null`. The specification says in this case I must throw a `MyObjectNotFoundException` so the code becomes something like this: ``` Vehicle vehicle = vehicleRepostory.findByIdInitialized(vehicleId); MyObjectNotFoundException.throwIfNull(vehicle, Vehicle.class, vehicleId); ``` What can I do if I want to get rid of calls to `throwIfNull`. It is not really DRY and a poor design choice anyway. There must be some design pattern unbeknownst to me. I searched on the web but it did not turn up anything really usable. A straightforward solution might be putting the code into my Repository but I use SpringData for this so it is just an interface: ``` public interface VehicleRepository extends Repository<Vehicle, Long> // ... @Query("select v from Vehicle v LEFT JOIN FETCH v.technicalData td LEFT JOIN FETCH v.registrationData rd" + " where v.vehicleId = ?") Vehicle findByIdInitialized(Long vehicleId); ```

Original source

Related problems