Immutable Strings
Author: Paul Bates
Introduction
On the heals of a point raised on eiffelroom regarding read-only variants of an Eiffel STRING, this page has come about to discuss the possible options for introducing such new types.
The term read-only is not a fitting name so this page documents such string variants as being immutable with it's already implemented cousins STRING_8 and STRING_32 coined mutable.
Rational
There are a number of reason why Eiffel needs an immutable representation of a string, which no matter what should be able to be altered. This leads to the first rationale. A constant is a constant. The moment a constant changes it's has introduced
EMCA STRING_8 and STRING_32
Section 8.29 of the Eiffel ECMA specification details the declaration and use of constants in Eiffel. To be padantic about the matter I extracted a dictional reference for the the word constant.
con·stant /ˈkɒnstənt/ –adjective 1. Not changing or varying; uniform; regular; invariable. –noun 7. Something that does not or cannot change or vary.
ECMA details the use of STRINGs as constants but in reality this is contracting to the definition and misleading in true semantics. STRINGs are mutable, "constant" or not. As a simple case example, take the following code snippet.
full_path: STRING_8 once Result := template_path Result.replace_sub_string_all ("$1", root_path) ensure result_attached: Result /= Void not_result_is_empty: not Result.is_empty end
template_path: STRING_8 = "$1\data\default.cfg"
The code demonstrates an all too common scenario. Once full_path has been called the contents of template_path are modified. Any other use of template path will yield a "contant" value that differs from that declared. The EMCA specification indicates that declaration of template_path pertains to the specification of a constant attribute (8.29.2 and 8.29.3.)
full_path, with once function semantics, is never a constant but is evaluated on a single as-needed basis. full_path actually demonstrates yet another rationale for introducing immutable strings into Eiffel.
A second rationale is through good design of a class' exported interface. A good design will yield immutable exported members as not to seemingly violate such principles of object orientation. I note "seemly" violated because
feature -- Access
selected_indexes: BILINEAR [NATURAL] -- Select item indexes do Result := internal_selected_indexes.twin ensure result_attached: Result /= Void end
feature {NONE} -- Implementation
internal_selected_indexes: ARRAYED_LIST [NATURAL] -- Mutable version of `internal_selected_indexes'
selected_indexes permits clients to access a list of index positions but never to extend of remove items from that structure. internal_selected_indexes is used internally to add or extend items based on some peripheral interaction.
As it stands today, with only mutable strings, this is not possible. A class attribute is open for modification by an unruly client.