April 29, 2004
Don't Return References to Mutable Objects
Don't Return References to Mutable Objects, says Adam Kolawa.
Absolutely right - but for the wrong reason, I think. The security concerns he cites are not the real problem - as Ted Neward points out, if somebody's running code in your VM, you are already dead. No, the problem with returning references to mutable objects is that it's a pistol. It's all to easy for someone else to hose your object by accident. What's more, if this happens, it's a really hard problem to diagnose. You can look at your classes code all day, and put as many breakpoints in there as you want to, and you'll never see where it goes wrong.
Trust me, I know. ;-)
See also Joshua Bloch's Effective Java (which I can't recommend too highly) and Java Practices: Immutable objects.
This is as pertinant to Python as it is to Java, BTW, as is much of Effective Java.
Posted to Java by Simon Brunning at April 29, 2004 01:07 PM
Yes, the whole point of OO programming is that you can shield the caller from the internal state of your object. Returning mutable objects violates the encapsulation. That's why there's Collections.unmodifiableList() and such.
Revevant to us burger flippers too :-)
Or rather, don't return references to mutable objects that you use internally in your objects, unless you want the caller to modify them directly. It's surely alright if you copy a Python list (used internally in your object) and return it from a method.
Yes, absolutly right, returning a *copy* of a mutable object is fine. It's returning a reference to a muable object that that represents part of your object's state that's deadly.
I recently found a case in some code of mine where I hosed my own objects by not paying close enough attention to the fact that I was mangling a reference rather than a copy. Boy, did I feel dumb.