开发者

Question about gets and sets and when to use super classes

开发者 https://www.devze.com 2022-12-31 22:06 出处:网络
I have the following get method: public List<PersonalMessage> getMessagesList() { List<PersonalMessage> newList = new ArrayList<PersonalMessage>();

I have the following get method:

public List<PersonalMessage> getMessagesList() {
    List<PersonalMessage> newList = new ArrayList<PersonalMessage>();

    for(Person开发者_JAVA百科alMessage pMessage : this.listMessages) {
        newList.add(pMessage.clone());
    }

    return newList;
}

And you can see that if I need to change the implementation from ArrayList to something else, I can easily do it and I just have to change the initialization of newList and all other code that depends on what getMessageList() returns will still work.

Then I have this set method:

public void setMessagesList(ArrayList<PersonalMessage> listMessages) {
    this.listMessages = listMessages;
}

My question is, should I use List instead of `ArrayList in the method signature?

I have decided to use ArrayList because this way I can force the implementation I want, otherwise there could be a mess with different types of lists here and there.

But I'm not sure if this is the way to go...


The setter method is breaking the abstraction of the underlying representation. Is it really needed on your public interface?

public void setMessagesList(Collection<PersonalMessage> messages) {
    this.listMessages = new ArrayList<PersonalMessage>(messages);
}


In general, I'd go for the interface (List). It means you don't break client code if you ever decide that ArrayList wasn't the correct thing to use in this situation.

You're also agreeing with yourself if you use List. The getter and the setter have the same type.

Another potential problem is that some reflection utilities may not recognize your getter/setter pair if they don't have the same type.


Do you depend on the order of the PersonalMessages, or would a Collection also be sufficient? Why would you want to force a specific implementation? For the code above a Paramater type of Collection, or even Iterable would be good enough.

0

精彩评论

暂无评论...
验证码 换一张
取 消