Mutate a Counter component's state through increment and reset methods.

← Dependency Injection · Ref: Q1109

Non-pure methods modify component state:

  increment()
    count++
  reset()
    count: 0

Pure methods (readers) use 'as pure'; non-pure methods (writers) do not. The compiler enforces this.

See Q1105 for basic components. See Q1106 for copying component state.

Example

defines module qa.di.componentmutation

  defines component

    Counter
      count <- 0

      increment()
        count++

      reset()
        count: 0

      getCount() as pure
        <- rtn as Integer: count

      default operator

  defines program

    ComponentMutationDemo()
      stdout <- Stdout()

      counter <- Counter()
      stdout.println(`Initial: ${counter.getCount()}`)

      counter.increment()
      counter.increment()
      counter.increment()
      stdout.println(`After 3 increments: ${counter.getCount()}`)

      counter.reset()
      stdout.println(`After reset: ${counter.getCount()}`)

Common mistakes

E08120 — Methods that modify state cannot be marked 'as pure'. Remove 'as pure' from mutating methods.

Incorrect:

      increment() as pure
        count++

Correct:

      increment()
        count++
Other ways to ask this
  • I need a component that tracks a count and provides methods to change it
  • In Java I'd have a mutable bean with setter methods. Write the EK9 equivalent
  • Given a counter component, call methods that modify its internal state
  • Build a stateful component and demonstrate state changes through method calls

Coming from another language?

Java: mutable service with fields and methods. Spring: @Service with state. EK9: component with mutable fields and non-pure methods.

Keywords: mutation, method, component, state, increment, mutable