Skip to content

refactor: Replace mutable read model methods with pure functions #160

@jwilger

Description

@jwilger

Context

During the implementation of multi-stream query patterns (#148), expert agents identified that the read models in src/infrastructure/eventcore/projections/read_models.rs use mutable methods instead of pure functions. This violates functional programming principles and makes the code harder to reason about and test.

Current Implementation

The read models currently have methods like:

pub fn add_request(&mut self, request_id: &RequestId, model_version: &ModelVersion) {
    self.total_requests += 1;
    self.models_used.insert(model_version.clone());
}

Proposed Solution

Refactor all read model methods to return new instances instead of mutating state:

pub fn with_request(self, request_id: &RequestId, model_version: &ModelVersion) -> Self {
    Self {
        total_requests: self.total_requests + 1,
        models_used: {
            let mut models = self.models_used;
            models.insert(model_version.clone());
            models
        },
        ..self
    }
}

Benefits

  • Immutable data structures
  • Easier to test and reason about
  • Thread-safe by default
  • Enables better composition

Tasks

  • Refactor SessionSummary methods to be pure
  • Refactor UserActivityModel methods to be pure
  • Refactor VersionPerformanceModel methods to be pure
  • Refactor ApplicationMetricsModel methods to be pure
  • Update all tests to use the new API
  • Update projection builder usage if needed

Labels

  • enhancement
  • technical-debt
  • functional-programming

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions