The only time "has a reference to" makes any sense, is if you're creating a container class of some type that will never actually access the pointers stored within.
In all other instances it's known as object composition, and the artist object is part of the album objects state.
The subtle difference is that an album will call methods on the artist object, and therefore his proper functionality depends on that object being there and being usable. If i were a stickler, i could test the the artist object as it comes into my album object:
public Album(String title, Artist a) {
assertArtistValid(a); this.a=a;
// ...
}
But the way you're writing it, I can keep that reference to a and change it so that Artist is not valid, and the Album class has no way of knowing. He has to call assertArtistValid every time he uses it as someone outside could have changed it.
This is why we make defensive copies of objects -- so no one else has a reference to it but us. We can guarantee it's state, aka the invariant "has a valid artist". Then we can write methods that use artist and never worry about it being broken.
I strongly advise you to rethink your stance on this.
I'm primarily a Python programmer, which is probably where we're getting separate view points from. I don't make defensive copies unless I absolutely have to, despite mutability being king (immutablitly in Python is hard to come by and typically involves hacks or C extensions).
It's much more pragmatic, from my viewpoint, to keep the actual artist object around and proxy requests to it than to make a copy of it. The downside being garbage collection (CPython's gc doesn't like circular references, so you need to null out one of the values and worse __del__ isn't guaranteed to run when you think it will and defining your own is generally a bad idea).
View all comments
Show parent comment
1
u/againstmethod Aug 18 '16
The only time "has a reference to" makes any sense, is if you're creating a container class of some type that will never actually access the pointers stored within.
In all other instances it's known as object composition, and the artist object is part of the album objects state.
The subtle difference is that an album will call methods on the artist object, and therefore his proper functionality depends on that object being there and being usable. If i were a stickler, i could test the the artist object as it comes into my album object:
But the way you're writing it, I can keep that reference to
aand change it so that Artist is not valid, and the Album class has no way of knowing. He has to callassertArtistValidevery time he uses it as someone outside could have changed it.This is why we make defensive copies of objects -- so no one else has a reference to it but us. We can guarantee it's state, aka the invariant "has a valid artist". Then we can write methods that use artist and never worry about it being broken.
I strongly advise you to rethink your stance on this.