Null check design pattern

  • No need to put if statement for checking null object
  • Use Factory Design Pattern and return a new class object to signify null values if NPE condition happens
public interface Vehicle {
    int getTankCapacity();
    int getSeatingCapacity();
}
 
 
public class Car implements Vehicle {
    @Override
    public int getTankCapacity() { return 40; }
    @Override
    public int getSeatingCapacity() { return 5; }
}
 
public class NullVehicle implements Vehicle {
    @Override
    public int getTankCapacity() { return 0; }
    @Override
    public int getSeatingCapacity() { return 0; }
}
 
 
public class VehicleFactory {
    static Vehicle getVehicleObject(String typeofVehicle) {
        if ("Car".equals(typeofVehicle)) {
            return new Car();
        }
        return new NullVehicle();
    }
}

Driver

public static void main() {
    Vehicle vehicle = VehicleFactory.getVehicleObject("Car");
    System.out.println(vehicle.getTankCapacity()); // will not throw NPE
    System.out.println(vehicle.getTankCapacity());
}