简体   繁体   中英

Force use of Integer instead int in method return

I have a set of methods tha read a property value and return the value in Integer , Float or String .

The problem is next:

In case that a developer make this:

int value = prop.getValueInteger("id.property");

In case that the method don't found the property or have a NumberFormatException , I will return null. The assignment fails in this case with NullPointerException. Same to the method Float version (Strings is covered because they don't use primitive with it)

I know that programmers can be forced to catch possible exceptions, but I preffer if there are any options to force the developer to use Integer instead of int.

To prevent developers just assigning to int , when you have a value which might not be present you can return Optional<Integer>

// never null
Optional<Integer> value = prop.getValueInteger("id.property");
if (value.isPresent()) {
    int v = value.get();

You can also value Optional<Float> and Optional<String> again to make handling of a value which might not be there explicit.

Another option is to never return null, but instead use a default.

int value = prop.getValueInteger("id.property", -1);

This assumes you can't throw a more useful exception like

public int getValueInteger(String name) throws IllegalStateException {
     Object v = getValue(name);
     if (v == null) throw new IllegalStateException("Property " + name + " not set.");
     return convertTo(Integer.class, v);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM