Problem
I need to execute the same set of statements but with a different name of the field each time. I was wondering if there is a better way to write this?
int returnCode = collectValue("empName", record);
if(returnCode <0)
{
return false;
}
returnCode = collectValue("empNum", record);
if(returnCode < 0)
{
return false;
}
returnCode = collectValue("empSalary", record);
if(returnCode < 0)
{
return false;
}
Solution
There are two primary ways I can think of to change this:
-
Iterate over an array
String[] fieldNames = new String[]{ "empName", "empNum", "empSalary" }; for (String field : fieldNames) { if (collectValue(field, record) < 0) { return false; } }
-
Boolean short-circuiting
boolean returnFalse = collectValue("empName", record) < 0 || collectValue("empNum", record) < 0 || collectValue("empSalary", record) < 0; if (returnFalse) { return false; }
I would personally recommend the first version, as the second version creates a long statement and is a bit more difficult to both read and debug.