I am a newbie and just started working on code, i have a task at hand and after doing a bit of research i am still not able to find the answer.
I have a java function which uses a lot of if else statements, my task is to optimize the code since nest if else is not very good programming so i've been told.
First i thought switch statement is the way to go but then i came across people telling to use map, i don't know what map is and the examples online are very hard to even understand.
Here is the code i have to optimize
public static Boolean SurveyValidObject(JSONObject jSONObject) {
Boolean message = false;
if (jSONObject != null) {
Iterator it = jSONObject.keys();
ArrayList<String> keysList = new ArrayList<String>();
while (it.hasNext()) {
String key = (String) it.next();
if (key.contains("field_")) {
int i = key.indexOf("_");
String _fieldValue = key.substring(0, i + 1);
keysList.add(_fieldValue);
} else {
keysList.add(key);
}
}
ArrayList<String> userDatalist = new ArrayList<String>();
userDatalist.add("survey_id");
userDatalist.add("source_id");
userDatalist.add("sso_id");
userDatalist.add("email_id");
userDatalist.add("field_");
Boolean returnValue = keysList.containsAll(userDatalist);
Iterator iterator = jSONObject.keys();
if (returnValue) {
while (iterator.hasNext()) {
try {
String key = (String) iterator.next(); // get key
String value = jSONObject.getString(key); // get value
if (key.equals("survey_id")) {
if (value == null) {
message = false;
break;
} else {
Boolean checkInteger = value.matches("\\d+");
if (!checkInteger) {
message = false;
break;
}
}
}
if (key.equals("crm_id")) {
if (value == null) {
message = false;
break;
} else {
Boolean checkInteger = value.matches("\\d+");
if (!checkInteger) {
message = false;
break;
}
}
}
if (key.equals("source_id")) {
if (value == null) {
message = false;
break;
} else {
Boolean checkInteger = value.matches("\\d+");
if (!checkInteger) {
message = false;
break;
}
}
}
if (key.equals("sso_id")) {
if (value == null) {
message = false;
break;
} else {
Boolean checkId = value.matches("^[ A-Za-z0-9\\\"\\$%^&()!*:;<>?{}_@.\\/#+-/'']*$");
String compareSSOValue = "/";
if (!checkId || compareSSOValue.equals(value)) {
message = false;
break;
}
}
}
if (key.equals("email_id")) {
if (value == null) {
message = false;
break;
} else {
message = value.matches("\\b[\\w.%-'-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b");
if (!message) {
break;
}
}
}
if (key.contains("field_")) {
int i = key.indexOf("_");
String _fieldValue = key.substring(i + 1);
Boolean checkInteger = _fieldValue.matches("\\d+");
if (checkInteger) {
message = true;
} else {
message = false;
break;
}
}
} catch (org.json.JSONException e) {
}
}
}
}
return message;
}