Designing classes to populate model in spring MVC

I want to populate data into the model from inside a controller.
Suppose there is a controller method  fetchResponse(Task task) That takes some Task object...
and returns a json TaskResponse object.

now here could be one implementation :

fetchResponse(Task task  @(RequestParam))

TaskResponse taskResponse = new TaskResponse(task);
return serialize taskResponse.

TaskResponse {

TaskResponse(Task task)
populate attributes

This is one way in which all the attributes of the TaskResponse object will be filled inside the TaskResponse object which will be serialized and sent .

Please suggest any pros and cons of this aproach... Also any alternatives.

Rohit BajajAsked:
Who is Participating?
girionisConnect With a Mentor Commented:
Ah.. ok, i see what you're doing. I thought you were using actual serialisation.

I would go with the second option,
new TaskResponse(task);

Open in new window

and populate the TaskResponse with the Task object in the constructor. You keep the controller cleaner and this is the usual way to populate objects if you know all the values at once.

An alternative would be to use the builder pattern if you have different parameters every time and you only need to populate some of them.

You could also consider static factory methods instead of passing the Task inside the constructor of TaskResponse.

By the way, these techniques (builder pattern and static factory methods) are described in detail in the book "Effective Java" (by Joshua Bloch). If you're concerned about writing better code and having a better design in you code I would definitely recommend it.
Why do you need serialisation? Do you send the response to another server? Why not simply set the Task to Model itself?

model.addAttribute("taskResponse", taskResponse);

Open in new window

Rohit BajajAuthor Commented:
The spring method is @ResponseBody
And so i can just send the TaskResponse object. probably spring serializes it automatically. Its about building the TaskResponse Object and then returning it.
The main question is about the design of code.  one way is  inside the controller only i do :
TaskResponse = new TaskResponse();
some looping to populate value

This pollutes the controller.
On the other hand the taskREsponse depends on task Object
So i can just do taskResponse = new TaskResponse(task);
And inside the constructor of the TaskResponse() i build up the TaskResponse object so the login for taskResponse stays inside TaskResponse.
This way the controller is not polluted with the code.
Wanted expert opions on this way the pros and cons some are cleaer..
And other alternative ways..
This is the correct answer.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.