Problems with Collection again.

Richard A. O'Keefe ok at cs.otago.ac.nz
Tue Feb 4 03:11:21 UTC 2003


Janet Abdul-Karim <jn_karim at yahoo.com> wrote:

	I made an instance of collection and trying to print out what is
	in the collection.  The way I coded seems to only print out the last
	obect that I added.

We're missing a lot of context here.

    Object subclass: #Portfolio
	instanceVariableNames: 'accounts '
	...

All I'm concerned with here is 'accounts'.
There is other information one might have about a portfolio,
such as who owns it, who manages it, its current value, &c.
	
	code
	
	portfolio: aAccount
	
	portfolio:= SortedCollection new.
	
	portfolio sortBlock:[:x :y | x name < y name].
	
	portfolio add: aAccount.
	
This is confusing.  A portfolio is not an account, and adding an account
is not the same as setting a portfolio.

Why is a SortedCollection used?  SortedCollections are costly (one might
even say _very_ costly) to update.  A variant of SortedCollection using
some kind of balanced binary search tree might be nice to have, but
SortedCollection itself is not such a data structure.

Let's use self-encapsulation to access 'accounts',
and within that, let's use lazy initialisation.
This way, the rest of the system NEVER sees a nil account collection.

    accounts
        accounts ifNil: [
	    accounts := SortedCollection new.
	    accounts sortBlock: [:x :y | x name < y name]].
	^accounts

Now if we ask for (aPortfolio accounts size) we don't have to worry
about nil.

    addAccount: anAccount
	^self accounts add: anAccount

Now thing slike (aPortfolio addAccount: anAccount) will work fine,
albeit slowly (order N).

	code to print portfolio
	
	portfolio isNil ifTrue:[Transcript show: 'Portfolio empty'].
	
	ifFalse:[portfolio do:[:element | Transcript show: element name]].
	
	***if you are wondering y i did not use isEmpty instead I tried and it was giving me errors turned out isNil worked just fine.  That fact that I could not use isEmpty make me wonder is porfolio is really a collection.***
	
Why bother with this at all?  Why not just "inspect" or "explore"
a Portfolio instance?  Or do this:

    printOn: aStream
	|sep|
	aStream nextPutAll: 'a Portfolio '.
	sep := $(.
	self accounts do: [:each |
	    aStream nextPut: sep.
	    each name printOn: aStream.
	    sep := Character space].
	aStream nextPut: $).

and then

    Transcript show: aPortfolio printString; cr.



More information about the Squeak-dev mailing list