Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

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

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 happen:

myLinkedList = anotherLinkedList;

So that I won't need to use setMyLinkedList(anotherLinkedList).

But! I need to add elements to it, or remove elements from it.

  • Should I write a new kind of setter to only, do the task of adding instead of setting, like myLinkedList.add(someElement)?

  • Or it is OK to do this by using getter, without disobeying Encapsulation principal?

    getMyLinkedList().add(someElement)

( + Suppose I am going to lose my mark if I disobey encapsulation :-")

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<String> myList = new ArrayList<String>();

    public List<String> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...