Immutable Strings

Revision as of 07:31, 17 April 2007 by Paulb (Talk | contribs) (Started page on immutable strings)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

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

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 above example demonstrates an all too common scenario. Once full_path has been called the contents of template_path are modified. The EMCA specification indicates that template_path is a constant declaration, it is not!

A second rationale is through good design of a class' exported interface. A good design will yield immutable exported members as not to violate the principles of object orientation.

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.