To give a little context before showing the problem:
I am creating a RESTful web application. A User can have multiple addresses, emails, phones and projects. Each of these is represented similar to the following object model, (Address in this case).
public class Address {
String type; //home or work etc.
String streetname;
/*some more things*/
Privacy privacy; //Privacy object
}
Every model contains a privacy object since a user can decide which of his addresses may be set to private (for instance only show the address to his contacts). The privacy object contains the following:
public class Privacy {
@Id
private String id;
private boolean showForNonContacts;
private boolean onlyShowForGroups;
/*
getters and setters
*/
}
The problem:
In my controller, I am fetching the userprofile object which contains these models. For every model, I have to check the following:
List<Address> visibleAddresses = new ArrayList<Address>();
for(Address address : userProfile.getAddresses()) {
if(address.getPrivacy().isShowForNonContacts() || hasContact) {
visibleAddresses.add(address);
}
userProfile.setAddresses(visibleAddresses);
}
//Same code repeats but now for email/phone/projects
I have to do this for the emails, phones and projects. This clearly is a bad design and I would like to make it better and cleaner than repeating the above code for every model. Does anybody have any tip of how I can make the above code work? I thought of using generics, interfaces where this method would be some what common, but I really don't know since I'd like to keep the model class clean.
Any tips/advice is greatly appreciated.
The UserProfile class should still contain a List for instance, since my db mapper (MongoDB/Spring data) has to recognize it as an embedded object.
EDIT: Based on the answer of Greg Burghardt, I decided to create a generic class called GenericCollection. Each of the models implements a separate interface. GenericCollection extends this interface and makes use of the method which controls the privacy (as defined in the interface).
Now the code is a lot cleaner.