Return to site

JAVA CERTIFICATION QUESTION: The Optional class and null values in Java

· java

Given:

public class Config extends Properties {
  static class ConfigException extends RuntimeException {    
    ConfigException(String message) {
      super(message);
    }
  }
  public String getProperty(final String key) {
    String property = super.getProperty(key);
    if (property == null) {
      throw new ConfigException(String.
                format("Missing value for key '%s'!", key));
    }
    return property;
  }  
  
  BiFunction<Boolean, String, Optional<String>> compose = 
    (flag, val) -> {
      return flag ? Optional.of(val) : Optional.empty();
    };  
  
  public Optional<String> getConfigString(String key) {
    return compose.apply(
       this.containsKey(key), this.getProperty(key)
    );  
  }
}

Call of the code below cause an exception:

Config cfg = ... // load config from file
var path= cfg.getConfigString("path");
String pathStr = path.orElseGet(() -> getDefaultPath());

Which approach will fix the problem? Choose one.

A. Wrap Config in ThreadLocal:

ThreadLocal tl = ThreadLocal.withInitial(() -> cfg);

B. Override put(Object, Object) and setProperty(String, String) to avoid storing null values in the Config class.

C. Use Optional.ofNullable(...) instead of Optional.of(...) in Config

D. Use a Supplier as a second parameter for the BiFunction.

 

 

 

 

 

 

 

·ꓷ uoᴉʇdo sᴉ ɹǝʍsuɐ ʇɔǝɹɹoɔ ǝɥꓕ