• Post Reply Bookmark Topic Watch Topic
  • New Topic

returning mutable objects and cloning  RSS feed

 
Zhia-zhia Xiu Bai
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I was doing some review and read about never returning a mutable object from an accessor method, but rather return a clone of it or else break encapsulation(and potentially expose it to unwanted changes). I am *sure* that at my last job there was tons of code that did not obey this rule.
Does anyone have advice about whether the clone is really practical in everyday use in say a model object class that has members being persisted with Hibernate to a db:


class SomeObject //would have to implement Cloneable here {

private Date foo;

public Date getFoo() {
//should return foo.clone();

return foo;
}

// implement public clone method
}
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a lot of design decisions you express - knowingly or not - whether you want an API to enable certain things in the clients, or enforce certain things. You also indicate how much you trust the clients to use the API exactly as you expect, and how much work you are willing to do to make the client's life easier.

Any of those forces could lead you to use the guidelines you read and never return mutable objects. It's often "more correct" to return non-mutable objects, but we get away with an awful lot of "not correct" things. I'm trying to deliberately push my concept of "good" code toward those "correct" things, but it isn't always easy.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!