Monday, September 28, 2015

Truthy values : Java parsing string to boolean

When i worked for a product company for 3 years, there was a lot of custom code made by many developers. And since we had over 20 customers there were a lot of settings and flag driven features.

Some developer would use 'yes' to denote something was true or enabled. Others would use 'Y' others would use 'true' and a few would be case in sensitive. For a few '1' was okay to denoate true.

Similarly false could be 'f', 'FALSE', 0, 'no' in strict case or case insensitive.

Made a small function to denote truthy  value parsing, along with a default (if null or that row missing from the RDBMS table).

boolean isTruthy(String value, boolean default){ 
 if(value == null || value.length()){
 char c = Character.toLowerCase(value.charAt(0)); 
 return c == 'y' || c == 't' || c=='1'; 
 }

reference :
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#toLowerCase%28char%29

No comments:

Post a Comment

Followers