简体   繁体   中英

how to write function for multiple if-else statements

I am new to Java. I have lots of multiple if-else statements. For code optimization purpose I need to write one function for all if else logic.

if (obj.getJSONObject("page_1").has("city")) {
    sn.city = (String) obj.getJSONObject("page_1").get("city").toString();
} else {
    sn.city = null;
}

// param 2 - locality

if (obj.getJSONObject("page_1").has("locality")) {
    locality = (String) obj.getJSONObject("page_1").get("locality").toString();
} else {
    locality = null;
}

I have like 110 if -else statements. I don't have any idea how to optimize the code.

I might write a function something like:

static String getToStringOrNull(JSONObject parent, String key) {
  return parent.has(key) ? parent.get(key).toString() : null;
}

which you can then call like

sn.city = getToStringOrNull(obj.getJSONObject("page_1"), "city");
locality = getToStringOrNull(obj.getJSONObject("page_1"), "locality");

I think the best use would be this notation ( ternary operator ):

sn.city = (obj.getJSONObject("page_1").has("city")) ? 
                    (String) obj.getJSONObject("page_1").get("city").toString() : null;

The part before ? stands for the if-statement, the second part if the condition was fulfilled and the last part otherwise.

For all direct fields of your class, you may use reflection (and you could do the same work on the sn object if you want ) :

Class aClass = this.getClass();

Field[] fields = aClass.getFields();

for (Field field : fields) {


   String value = (obj.getJSONObject("page_1").has(field.getName())) ?
            (String) obj.getJSONObject("page_1").get(field.getName()).toString() : null;

   field.set(this, value);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM