Tuesday, 6 March 2018

1. Life's Persistent Questions Puzzle


public class SimpleQuestion {
    static boolean yesOrNo(String s) {
        s = s.toLowerCase();
        if (s.equals("yes") || s.equals("y") || s.equals("t"))
            s = "true";
        return Boolean.getBoolean(s);// or Boolean.parseBoolean(s);
    }

}

    public static void main(String[] args) {
        System.out.println(
                yesOrNo("true") + "" + yesOrNo("Yes"));
    }
}

Answer : false false
What does Boolean.getBoolean do?
public static boolean getBoolean (String name)            

Returns true if and only if the system property named by the argument exists and is equal to thestring "true". (Beginning with version 1.0.2 of the Java platform, the test of this string is case insensitive.)
A system property is accessible through getProperty, a method defined by the System class
If there is no property with the specified name, or if the specified name is empty or null, then false is returned.

Best Right Solution: 

return s.equals("yes") || s.equals("y") || s.equals("true") || s.equals("t");

The Moral
1. Strange and terrible methods lurk in libraries 
  • Make sure you're calling the right methods(some deprecated method )
  • Some have innocuous sounding names
2. If your code misbehaves
  • Read the library documentation
3. For API designers
  • Don't violate principle of least astonishment (great surprise,Shock)
  • Don't violate the abstraction hierarchy(low level to High Level)
  • Don't use similar names for wildly different behaviors

No comments:

Post a Comment