Dodo doc > Macros and Templates > Templates > Type With Abstract State


Type With Abstract State

Abstract state allows a same type to change according to the internal state of the instance. The attributes, methods, functions and subtypes can all be redefined for each state.

Advantages
Flexibility to move between states
Inconvenients
The transitions are controlled only by the abstract state
Abstract state is dynamic and can require more instructions
Doesn't necessarily encourage the reuse of code

Example:

class Player is Mutable:
   __state stopped =>
      method Play(Media)
   __state started.playing =>
      method Stop()
      method Pause()
   __state started.on_pause =>
      method Resume()
      method Forward(int)
.

Use:

Player player
player.Play(music)
 # player state is started.playing, only allows Stop() or Pause()

The abstract state of a variable can be tested by adding an apostrophe and the state name to the matched type (optional).

Example:

player ~ ?'started

If the type is Polymorphic, the abstract state can be included when checking type compatibility.

Example:

T ~ Player'started
Rationale: rather than producing a family of types based on a template, abstract state produces a single type which can replace multiple types. Like with type templates, these multiple types can share code when they are unified into a single type with abstract state.
The matching rules are useful since abstract state is dynamic. In the case of a polymorphic type, each state can be considered a subtype of the main type which makes the abstract state part of the type.

^ 5.4.1 Type With Attributes

v 5.4.3. Type Template