I have a Java Spring batch step, which collets all the data for the next writing step. This controller message collects data from several datasources. After collecting, all the date is put into a result object which gets returned to the caller method. This is my pseudo code method:
public ReturnObject collectData() {
List<A> a = getDataA();
...
List<Z> z = get dataZ();
ReturnObject o = new ReturnObject();
o.setA(a);
...
o.setZ(z);
return o;
}
In this example it looks not so ugly, but I have to call about 15 of those methods and the method is grown very long.
Is there a better pattern to structure such a method.
I could do something like:
populateDataAIntoReturnObject(returnObject);
but this would hide the writing process into the return object in the sub-method.
Is there a better pattern for such data collecting methods?
CodePudding user response:
As mentioned it's hard to help you without a more complete idea of what you are doing. This beeing said I think populateDataAIntoReturnObject(returnObject)
seems a bit worse than what you currently have. Returning a object instead of filling in a parameter gives you more control. You could for example cache objects in the future which isn't possible if you always need to create a new one to provide it as a parameter.
There are quiet a few patterns, that you could use (Repository
, Service
etc.), but they are more about hiding the implementation instead of structuring your code.
CodePudding user response:
You should rather create a public method populateData() within ReturnObject class which will set its own member variables. So code block will look like this.
public class ReturnObject {
...
public void populateData () {
List<A> a = getDataA();
...
List<Z> z = get dataZ();
setA(a);
...
setZ(z);
}
}
And you can use the class like this
...
ReturnObject o = new ReturnObject();
o.populateData ();
CodePudding user response:
You can use Service-classes. One "head" service-class collects data from other services and represents it to controller