VOOZH about

URL: https://www.javacodegeeks.com/2016/04/converting-string-configuration-properties-types-bit-optional.html

⇱ Converting string configuration properties to other types, with a bit of Optional - Java Code Geeks


Somedays you come across some code and think that’s pretty, why didn’t I think of that? So my long time colleague Mark Warner has a nice twist on the standard name/value store pattern using method references to deal with converting from a String.

int size = store.getProperty("cache.limit", 500, Integer::parseInt);
 boolean enabled = store.getProperty("cache.enabled", true, Boolean::getBoolean);

I took his example and refactored it slightly to return Optional, and I ended up with the following:

public Optional<String> getProperty(
 String propertyName) {
 return Optional.ofNullable(map.get(propertyName));
}
 
public <T> Optional<T> getProperty(
 String propertyName, 
 ThrowingFunction<String,? extends T,? extends Exception> func ) {

 return getProperty(propertyName).map(val -> {
 try {
 return func.apply( val );
 } catch ( Exception e ) {
 LOGGER.severe( () -> "Invalid property transform, will default " + e.getMessage() );
 return null;
 }
 });
}

This means that the default value ends up being provided by the Optional which is a nice application of OAOO.

int size = store.getProperty("cache.limit", Integer::parseInt).orElse(500);
 boolean enabled = store.getProperty("cache.enabled", Boolean::getBoolean).orElse(true);

I think this is even tidier; but it does depend on who you feel about using Optionals.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Gerard Davison
Gerard Davison
April 11th, 2016Last Updated: April 8th, 2016
0 88 1 minute read
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz