Friday, May 11, 2018

When Yes and No is not enough.

In typical world Boolean works just fine. Every time we need a flag we declare a boolean data type and its over.
But now here comes a situation where yes and no answer is not always enough.
Lets take an example, with following questions?
is this user has a valid credit card? we can answer this with yes or no but typically there should be three answer choices
  • yes
  • no
  • i do not know
i do not know is not definitely equivalent to yes or no.
Java Exception Issue
In java if exception arise while parsing a json token for a boolean it will set as false;
JSONObject response=new JSONObject();
boolean flag=false;
try {
    flag=response.getBoolean("valid_card");
} catch (JSONException e) {
    e.printStackTrace();
}
System.out.println(flag);
if an exception occurs while getting valid_card token and result could be true or false depend on how we initialized it. But that doesn't really represent real case.
Solutions?
Ultimately we can simply avoid whole things by creating an enum which can have three different value
public enum EnumBoolean {
    TRUE(10), FALSE(20), UNDEFINED(30);
    private final int code;
    private static final Map<Integer,EnumBoolean> lookup
            = new HashMap<Integer,EnumBoolean>();
    static {
        for(EnumBoolean w : EnumSet.allOf(EnumBoolean.class))
            lookup.put(w.getCode(), w);
    }
    public int getCode() { return code; }

    EnumBoolean(int value) {
        this.code = value;
    }
    public static EnumBoolean fromInt(int value){
        switch (value){
            case 10:
                return TRUE;
            case 20:
                return FALSE;
        }
        return UNDEFINED;
    }
    public static EnumBoolean get(int code) {
        return lookup.get(code);
    }
}
Now if we rewrite our existing java code
JSONObject response=new JSONObject();
    EnumBoolean flag=EnumBoolean.FALSE;
    try {
        flag=EnumBoolean.fromInt(response.getInt("valid_card"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    System.out.println(flag);
Now if an error occur while parsing valid_card, final flag value would be undefined.
And, off-course this things to work backend server must consider sending boolean values as an int. and int 10 in this case.

No comments: