Is it a bad practice to add elements to List using getter method in java?

前端 未结 6 2062
北海茫月
北海茫月 2020-12-15 20:44

Suppose I have a private ArrayList or a LinkedList inside a class, that I will never assign new reference to it, or in other words this will never

6条回答
  •  时光说笑
    2020-12-15 21:07

    I don't think it a particularly great practice to do something like:

    myObj.getMyList().add(x);
    

    since you are exposing a private class variable in a non read only way, but that being said I do see it pretty frequently(I'm looking at you, auto generated classes). I would argue that instead of doing it that way, return an unmodifiable list and allow users of the class to add to the list via an explicit method:

    public class MyClass{
        private final List myList = new ArrayList();
    
        public List getList(){
            return Collections.unmodifiableList(this.myList);
        }
    
        public void addToList(final String s){
            this.myList.add(s);
        }
    }
    

    EDIT After reviewing your comments, I wanted to add a bit about your setter idea:

    I meant using that line of code inside a new kind of setter inside the class itself, like public void setter(someElement){this.myLinkedList.add(someElement);}

    If I'm understanding you correctly, you are saying you want to expose a method that only adds to your list. Overall this is what I think you should be shooting for, and what many have outlined in the answers, however, labeling it as a setter is a bit misleading since you are not reassigning (setting) anything. That, and I strongly recommend returning a read only list from your getter method if possible.

提交回复
热议问题