Parameterizing a common template [closed]

Posted on

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:

  1. Iterate over an array

    String[] fieldNames = new String[]{ "empName", "empNum", "empSalary" };
    for (String field : fieldNames) {
        if (collectValue(field, record) < 0) {
             return false;
        }
    }
    
  2. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *