diff --git a/documentation/current/examples/example-self-initializing-attributes-and-assigner-commands.wiki b/documentation/current/examples/example-self-initializing-attributes-and-assigner-commands.wiki new file mode 100644 index 00000000..54984d24 --- /dev/null +++ b/documentation/current/examples/example-self-initializing-attributes-and-assigner-commands.wiki @@ -0,0 +1,85 @@ +[[Property:title|Example: self-initializing attributes and assigner commands]] +[[Property:link_title|Example: Self-initializing attributes and assigner commands]] +[[Property:weight|0]] +[[Property:uuid|dbc107a4-42cd-606a-71b2-e0b70ac5482e]] +==Description== + +Example of using a [[Void-safety: Background, definition, and tools#Self-initializing attributes|self-initializing attribute]] and an [[ET: The Dynamic Structure: Execution Model#Assigner commands|assigner command]]. + +==Notes== + +The concepts of [[Void-safety: Background, definition, and tools#Self-initializing attributes|self-initializing attributes]] and [[ET: The Dynamic Structure: Execution Model#Assigner commands|assigner commands]] are independent of one another. However, this example shows how each works in a small amount of code. + +The example consists of two classes: a root class, and class PERSON. The PERSON class has a self-initializing attribute of type STRING named mood. If mood is accessed before it is explicitly initialized, then the self-initializing code after the keyword attribute will be executed, setting the default mood to "Happy". + +The attribute mood also has an assigner command, the procedure set_mood, designated as such by the assign keyword. This allows clients of class PERSON to appear to assign directly to mood. However, the assigner command set_mood will always get executed, and its precondition will be in force during such an apparent assignment. + +The root class APPLICATION creates an instance of PERSON and prints the value of mood, getting the self-iniitalized value. Then it assigns to mood. When it prints again, it gets the updated value. + +==Source== + +Adapted from an example given on the Eiffel Software Users Group. + +==Solution== + +A root class: + + +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Print and set mood of `my_person'. + do + create my_person + print ("Mood: " + my_person.mood + "%N") + my_person.mood := "Ecstatic" + print ("Mood: " + my_person.mood + "%N") + end + +feature -- Access + + my_person: PERSON + +end + + + +Class PERSON: + + +class + PERSON + +feature -- Access + + mood: STRING assign set_mood + attribute + Result := "Happy" + end + +feature -- Element change + + set_mood (a_string: STRING) + require + single_token: a_string.occurrences (' ') = 0 + do + mood := a_string + ensure + mood_set: mood = a_string + end +end + + +==Output== + + +Mood: Happy +Mood: Ecstatic + +