Reputation: 21
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.
Upvotes: 0
Views: 122
Reputation: 17534
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);
}
Upvotes: 0
Reputation: 140318
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");
Upvotes: 5
Reputation: 1123
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.
Upvotes: 2