[Newbies] Overriding methods

Blake blake at kingdomrpg.com
Sun Jan 20 23:35:34 UTC 2008


On Sun, 20 Jan 2008 07:54:47 -0800, Ron Teitelbaum <Ron at USMedRec.com>  
wrote:

> Hi Blake,
>
> There are a number of ways to initialize an object.  Overridding #new is  
> an acceptable practice but normally this is done because you do not want  
> a new object created.  For example if you wanted to have only one  
> instance of an object you might override #new to lookup your instance  
> and return that
> instead.

Sure, for singletons. Good example.

> Sometimes calling #new on class is a bad idea, either this class  
> shouldn't have instances, or there are other instance creation methods  
> that should be called instead.  (We usually don't override new because  
> of other instance
> creation methods but I can understand the argument if someone did)

Right. And while that's not necessarily ideal, I think it can be construed  
as part of the price of knowing how to use an object. (Though I like  
"contract-less" programming, do the degree it's possible.)

> FishTank class>>newForGallons: numberOfGallons
> 	"Create a fishTank that holds numberOfGallons"
> 	aTank := super new.  "call super to bypass error"
> 	aTank numberOfGallons: numberOfGallons.
> 	aTank calculateGlassForGallons.
> 	aTank calculateTopSizeForGallons.
> 	aTank calculateNumberOfLightsForGallons.
> 	^aTank
>
> Ok so this is kinda silly but I hope you get the idea.  This is what  
> happens when I make stuff up on the spot!

Well, no, this is precisely the sort of situation I run into all the time.  
"Gee, mister, I'd love to create an instance for ya, but I need to know  
what kind of instance you want."

> Ok so in most cases you can set your object up in #initalize
>
> FishTank>>initialize
> 	"set up default values for aFishTank"
> 	self glassSides: OrderedCollection new.
> 	self numberOfLights: 0 copy.
> 	self tankShape: #rectangle
>
> but you might want to change that setup during instance creation.

This also doens't solve your number of gallons issue. Which puts you in  
the position of changing that number of gallons after the instance is  
created.

> You could also extend your class hierarchy to support different tanks.

Yes. This something that I'm getting used to.

Thanks, Ron.




More information about the Beginners mailing list