i have the following implementation
public class PartGroup {
private Part iPart;
private ArrayList<Part> iParttList;
public Part getPart() {
return iPart;
}
public void setPart( Part aPart ) {
iPart = aPart;
}
public ArrayList<Part> getParttList() {
return iParttList;
}
public void setParttList( ArrayList<Part> aParttList ) {
iParttList = aParttList;
}
}
Is it ok to have setters for iParttList and iPart ? i think it is safe to have a getter only then the consumer can use getter to get the created instance of the collection and clear or add elements to the collection should i remove the setter and add the following implementation
public ArrayList<Part> getParttList() {
if(iParttList == null)
iParttList = new ArrayList<Part>();
return iParttList;
}
public Part getPart() {
if(iPart == null)
iPart = new Part();
return iPart;
}
What is the best practice?
The second implementation guards against returning null, right? So if there's a chance this object could return null (because what constructors there are permit this or it otherwise could come to pass) and that would be a Bad Thing for your intended use case, then use the second implementation.