Comment 1.
You probably meant to write
tracks: aCollection
^tracks := aCollection
Comment 2.
This is a poor design. As it is, any object can replace the tracks of an
artist
with *anything*. And even without doing that, any object can add and
remove
items to an artist's tracks, even if the added items are not Tracks.
There are a number of OO design principles, notably the Law of Demeter and
of course the GRASP patterns, which basically say "never mutate another
object's parts, ask IT to do the mutation."
I have come to regard the self-encapsulation "pattern" as an anti-pattern.
This is Smalltalk heresy, admittedly, but it doesn't so much break (real)
encapsulation as set it on fire, defenestrate it, and urinate on the
smouldering remains.
So this is the way I'd do it.
Object subclass: #Artist
instanceVariableNames: 'tracks'
methods for: 'initialising'
initialize
tracks := OrderedCollection new.
^self
methods for: 'checking'
invariant
^(tracks isMemberOf: OrderedCollection) and: [
tracks allSatisfy: [:each | each isKindOf: Track]]
methods for: 'accessing tracks'
addTrack: aTrack.
tracks add: aTrack.
^track
tracksDo: doBlock
tracks do: doBlock
with no way for outside code to accesss 'tracks' directly.
On Thu, 25 Jul 2019 at 02:47, sergio ruiz <[email protected]> wrote:
> I'm implementing an instance variable as an OrderedCollection, and am
> doing something idiotic.
>
> I have an Artist class.
>
> An Artist can have many tracks:
>
> tracks
> ^ tracks ifNil: [ self tracks: OrderedCollection new ]
>
> tracks: anObject
> tracks := anObject
>
> Doing something like:
>
> a := Artist new.
> t := Track new.
> a tracks add: t
>
> Gives me the error:
>
> Artist(Object)>>doesNotUnderstand: #add:
>
> Once I get past that error, which will evaluate `a tracks`, I can run this.
>
> I get why it works the second time, but I don't get why it thinks the
> instance of Artist is the receiver of add: on the first run.
>
> Thanks!
> ----
> peace,
> sergio
> photographer, journalist, visionary
>
> Public Key: http://bit.ly/29z9fG0
> #BitMessage BM-NBaswViL21xqgg9STRJjaJaUoyiNe2dV
> http://www.codeandmusic.com
> http://www.twitter.com/sergio_101
> http://www.facebook.com/sergio101
>
>