Esteban A. Maringolo wrote
> 2017-08-05 19:21 GMT-03:00 Peter Uhnak <

> i.uhnak@

> >:
> 
>> If I want to initialize the value in a separate method (typically for
>> testing or reuse), then I prefer to avoid state mutation there and
>> instead I return the result.
>>
>> MyClass>>#property
>>         ^ property ifNil: [ property := self createNewProperty ]
>>
>> MyClass>>createNewProperty
>>         "I won't touch property instance variable here, just create a new
>> value and return it"
>>         ^ self bar collect: [ :e | e drink ]
>>
>>
>> > an initializationMethod returning the value instead of the receiver is
>> a code smell to me.
>>
>> For this reason I tend to name such methods createNewX, initializeX says
>> to me "only mutate state and return self"
> 
> I like this approach very much, it makes the accessor code concise and
> separates the implementation of the property creation.
> 
> Thank you!
> 
> Esteban A. Maringolo

+1.
It also avoids having to dive a level deeper in a debugger when you want to
inspect the current value vs initial value without modifying state. 

For naming, I tend to use one of several depending on the use; 
a) initialX
b) defaultX
c) calculateX 
depending on whether the property is 
a) expected to change value during the lifetime of the object
b) have an optional value provided at creation, then be static
c) always be calculated (ie, an instvar used to cache expensive results used
often)

Cheers,
Henry 



--
View this message in context: 
http://forum.world.st/Lazy-initialization-patterns-tp4958897p4959054.html
Sent from the Pharo Smalltalk Users mailing list archive at Nabble.com.

Reply via email to