Example: Self-initializing attributes and assigner commands
- Contents
- Description
- Notes
- Source
- Solution
- Output
Description
Example of using a self-initializing attribute and an assigner command.
Notes
The concepts of self-initializing attributes and 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