在java中使用getter方法向List添加元素是不好的做法? [英] Is it a bad practice to add elements to List using getter method in java?

查看:401
本文介绍了在java中使用getter方法向List添加元素是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个类中有一个 private ArrayList 或一个 LinkedList ,我将永远不会分配新的引用它,或换句话说,这将永远不会发生:

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;

这样我就不需要使用 setMyLinkedList(anotherLinkedList)

但是!我需要添加元素,或从中删除元素。

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


  • 我应该写一种新的 setter to only,执行添加而不是设置的任务,如 myLinkedList.add(someElement)

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

或者可以使用<$ c $来做到这一点c> getter ,不违反 Encapsulation principal?

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 :-")

推荐答案

我不认为做一些特别好的做法:

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);
    }
}

编辑审核完毕后评论,我想补充一下你的setter想法:

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


我的意思是在一个新的setter里面使用那行代码类本身,如public void setter(someElement){this.myLinkedList.add(someElement);}

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);}

如果我理解你正确地说,您要说的是要公开仅添加到列表中的方法。总的来说,这就是我认为你应该拍摄的内容,以及许多人在答案中概述的内容,然而,将其标记为制定者有点误导,因为你没有重新分配(设置)任何东西。那,我强烈建议如果可能的话,从你的getter方法中返回一个只读列表。

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.

这篇关于在java中使用getter方法向List添加元素是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆