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

前端 未结 6 2060
北海茫月
北海茫月 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:15

    It depends on the application - both are acceptable. Take a good look at the class you're writing and decide if you want to allow users to directly access the contents of the list, or if you would prefer that they go through some intermediate process first.

    For example, say you have a class ListEncrypter which holds your MyLinkedList list. The purpose of this class is to encrypt anything that is stored in MyLinkedList. In this case, you'd want to provide a custom add method in order to process the added item before placing it in the list, and if you want to access the element, you'd also process it:

    public void add(Object element)
    {
        MyLinkedList.add(encrypt(element););
    }
    
    public Object get(int index)
    {
        return decrypt(MyLinkedList.get(index););
    }
    

    In this case, you clearly want to deny the user's access to the MyLinkedList variable, since the contents will be encrypted and they won't be able to do anything with it.

    On the other hand, if you're not really doing any processing of the data (and you're sure you won't ever need to in the future), you can skip creating the specialized methods and just allow the user to directly access the list via the get method.

提交回复
热议问题