[Cuis-dev] instance creation best practices
Juan Vuletich
juan at cuis.st
Thu Jun 13 06:24:55 PDT 2024
Hi Mark,
On 6/13/2024 9:58 AM, Mark Volkmann via Cuis-dev wrote:
> Suppose I want to define a Dog class that has the instance variables
> name and breed and I want the instances to be immutable. Is this the
> recommended way to define it?
>
> Object subclass: #Dog
> instanceVariableNames: 'breed name'
> classVariableNames: ''
> poolDictionaries: ''
> category: 'MyCategory'
>
> With this class method:
>
> name: aName breed: aBreed
> ^self new initializeName: aName breed: aBreed
>
> And with these instance methods:
>
> initializeName: aName breed: aBreed
> name := aName.
> breed := aBreed
>
> breed
> ^breed
>
> name
> ^name
>
> If I want the following to be the only way to create an instance:
>
> Dog name: 'Comet' breed: 'Whippet'
>
> would I do something to prevent using this?
>
> Dog new
>
> --
> R. Mark Volkmann
> Object Computing, Inc.
That looks good. See, for instance Point. In addition to what you did,
the setter message begins with 'initializePvt'. This gives a warning if
you try to call it from another class. It is also in a method category
that clearly says it is private.
If you want additional protection, `Feature require: 'Immutability'`,
and see #beImmutable and #beMutable .
Cheers,
--
Juan Vuletich
cuis.st
github.com/jvuletich
researchgate.net/profile/Juan-Vuletich
independent.academia.edu/JuanVuletich
patents.justia.com/inventor/juan-manuel-vuletich
linkedin.com/in/juan-vuletich-75611b3
twitter.com/JuanVuletich
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.cuis.st/mailman/archives/cuis-dev/attachments/20240613/4746ecd8/attachment.htm>
More information about the Cuis-dev
mailing list