public static void prepareOutput (Output[] parOutput, Input inputObj)
{
int arraySize = parOutput.length;
Output[] output = new Output[arraySize];
for(int i=0; i<arraySize; i++)
{
if(parOutput != null && parOutput[i].getSubscriptionsX7() != null)
{
output[i] = new Output();
output[i] = setLevel1OutputObj(parOutput[i],inputObj, output[i]);
output[i] = setLevel2OutputObj(parOutput[i],inputObj, output[i]);
output[i] = setLevel3OutputObj(parOutput[i],inputObj, output[i]);
output[i] = setLevel4OutputObj(parOutput[i],inputObj, output[i]);
}
}
inputObj.setSubscriberInfoOutput(output);
}
I have main Input object o1
which consists of object o2
. Object o2
consists of object o3
. Object o3
consists of object o4
.
Here I am passing the same output object in the argument and have it as return type as well. Can it be coded better?
输入inputObj
使其成为类成员,因此您的方法仅将parOutput
作为参数。
One option is to write a utility/helper function, like so:
public static Output configuredOutput(Output source, Input input) {
if (source.getSubscriptionsX7() == null) {
return null;
}
Output result = new Output();
result = setLevel1OutputObj(source, input, result);
result = setLevel2OutputObj(source, input, result);
result = setLevel3OutputObj(source, input, result);
result = setLevel4OutputObj(source, input, result);
return result;
}
...and then implement your loop-body in the calling code like:
if(parOutput != null && parOutput[i].getSubscriptionsX7() != null) {
output[i] = configuredOutput(parOutput[i],inputObj);
}
Another option, and what I think you're actually asking about, is to implement method-chaining . To do that you'd have to refactor your setLevelXOutputObj
functions to be instance methods on the Output
class.
If you did so, you'd then be able to rewrite your loop-body with something like:
Output source = parOutput[i];
output[i] = new Output().setLevel1OutputObj(source, inputObj)
.setLevel2OutputObj(source, inputObj)
.setLevel3OutputObj(source, inputObj)
.setLevel4OutputObj(source, inputObj);
The fact that you're always passing the Object
that you're working with as the final argument to your static functions is a good indication that your static functions would be more appropriately implemented as instance methods.
Note that as pbabcdefp states, you likely also want to look at your parOutput != null
check. You don't really have it in a reasonable place, as your current code will throw a NullPointerException
if parOutput
is ever actually null
.
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.