So, I've come across this situation
I have a Restful controller method which returns a list
of objects Match
@RequestMapping(value = "/fetchFootballMatchesToday", method = RequestMethod.GET)
public @ResponseBody List<Match> fetchMatchesScheduledToday() throws ParseException {
return matchesToday;
}
The object Match
has say 15 properties & I need only 3 properties on the UI. I do not want the user to see the other properties of the object.
There are two ways to do it:
Run a for loop & explicitly set the properties to null, for every
Match
object, which are not meant to be sent to the UI. Like soList<Match> matchesToday = matchInvService.fetchMatchByDate(today); for (Match stats : matchesToday) { if (stats != null) { /* user should not know these details, so they are being set to null */ stats.setMatchSuccessIndex(null); stats.setTeamRanking(null); stats.setStadiumInfrastructureLevel(null); ..... & so on } }
The problem with this approach is as the number of properties add up in future. This code needs to be updated too. Also, if the number of properties of an object is large. I need to keep setting null here, that many times.
Second approach is create a new Match object within the loop & just set the 3 required values to it.
List<Match> matchesToday = matchInvService.fetchMatchByDate(today); List<Match> responseList = new ArrayList<Match>(); for (Match stats : matchesToday) { if (stats != null) { Match tmpMatch = new Match(); match.setProperty1(stats.getProperty1()); } responseList.add(tmpMatch); } return responseList;
This approach creates additional Match objects every time the loop runs. Also, the creation of objects spike up if that particular method is called too often. Though the objects will be garbage collected, I ain't sure if this is an optimal way.
Need your suggestion guys. Is this a trade off between writing more code vs saving memory? What would be the best approach to tackle this?