I have the following class which I’m fighting over how to implement. The question is whether or not it makes sense to have a private collection item, in this case an arraylist, a a member. I am well aware it is considered best practice to have getters and setters for any class members, but in this case having a getter and setter would require re-implementing (or rather duplicating) large amounts of the ArrayList functionality.
Example class:
public class Email
{
private ArrayList<String> To;
private ArrayList<String> Cc;
private ArrayList<String> Bcc;
...
}
I assume the answer is I should indeed implement getters and setters for these arrays? Is there some approach I haven’t thought of regarding handling this type of situation? The easy solution to managing these lists is to set the private modifiers to public and check the array data is valid on calling methods, but is this right? Can anyone point me in the direction of other SO questions, design patterns etc I should consider?
Actually in that case I think it would be better to not provide a direct getter/setter combination.
I would rather approach it the following way:
List<String>(best practice to use Interfaces on fields.)ArrayLists in the constructor.add,remove,hasTo/Cc/Bcc.In that way you could decorate each collection with additional functionality, e.g. making sure the String contains a valid recipient information.
EDIT
I forgot to mention that a getter makes sense since you need that when processing the Email. But look at the other answer on considering to returning an unmodifiable
List.