Saturday, May 28, 2011

true and really true: what's the difference?

I was forced to return to the murky depths of the Java-Web Services marsh and specifically to the quadrant dominated by Axis2 and a variation of it adopted by a behemoth peddling an enterprise-grade application container. This is what they called nostalgia (for those who do not enjoy etymology, that almost literally means a return to pain). As the flashbacks ensued, I found myself drawn to an old favourite in the Axis2 code base, org.apache.axis2.util.JavaUtils. The class contains several methods that seem dedicated to an exploration of verity and falsitude. Here are the methods devoted to the truth, the whole truth and all variants of it.

/**
   * Tests the String 'value':
   * return 'false' if its 'false', '0', or 'no' - else 'true'
   * Follow in 'C' tradition of boolean values:
   * false is specific (0), everything else is true;
   */
  public static boolean isTrue(String value) {
    return !isFalseExplicitly(value);
  }

  /**
   * Tests the String 'value':
   * return 'true' if its 'true', '1', or 'yes' - else 'false'
   */
  public static boolean isTrueExplicitly(String value) {
    return value != null &&
        (value.equalsIgnoreCase("true") ||
            value.equals("1") ||
            value.equalsIgnoreCase("yes"));
  }

  /**
   * Tests the Object 'value':
   * if its null, return default.
   * if its a Boolean, return booleanValue()
   * if its an Integer,  return 'false' if its '0' else 'true'
   * if its a String, return isTrueExplicitly((String)value).
   * All other types return 'true'
   */
  public static boolean isTrueExplicitly(Object value, boolean defaultVal) {
    if (value == null) {
      return defaultVal;
    }
    if (value instanceof Boolean) {
      return ((Boolean) value).booleanValue();
    }
    if (value instanceof Integer) {
      return ((Integer) value).intValue() != 0;
    }
    if (value instanceof String) {
      return isTrueExplicitly((String) value);
    }
    return defaultVal;
  }

  public static boolean isTrueExplicitly(Object value) {
    return isTrueExplicitly(value, false);
  }

  /**
   * Tests the Object 'value':
   * if its null, return default.
   * if its a Boolean, return booleanValue()
   * if its an Integer,  return 'false' if its '0' else 'true'
   * if its a String, return 'false' if its 'false', 'no', or '0' - else 'true'
   * All other types return 'true'
   */
  public static boolean isTrue(Object value, boolean defaultVal) {
    return !isFalseExplicitly(value, !defaultVal);
  }

  public static boolean isTrue(Object value) {
    return isTrue(value, false);
  }

Needless to say, there are similar methods that handle the dark side. Jack Nicholson's famous line from A Few Good Men would be the best summary of a code review, should one ever happen.

No comments:

 
Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.