Skip to content

Fix accidental mutable static state and dead side-effect in ChamberOfEchoes #42

@liubchigo

Description

@liubchigo

Bug: Accidental mutable static state in ChamberOfEchoes

File: Solutions/CSharp/The-Chamber-of-Echoes.cs, lines 3–4

Problem

Both echoes and memories are declared as static class-level fields:

static List<int> echoes = new List<int> { 3, 6, 9, 12 };
static List<int> memories = new List<int>();

This causes two issues:

  1. memories is never used in any output — it's dead, accumulated state. Each call to PredictNext appends to it permanently, but nothing reads it back.
  2. State persists across calls — in any context where Run() is called more than once (e.g., tests, REPL), the memories list grows unboundedly, and the echoes list is shared global mutable state.

Fix

Move both lists to be local variables inside Run() and remove the memories side-effect entirely from PredictNext:

public class ChamberOfEchoes
{
    static int PredictNext(List<int> echoes)
    {
        int difference = echoes[1] - echoes[0];
        return echoes[echoes.Count - 1] + difference;
    }

    public static void Run()
    {
        var echoes = new List<int> { 3, 6, 9, 12 };
        Console.WriteLine(PredictNext(echoes));
    }
}

Impact

Code correctness and educational quality — this is a teaching repo, and the current pattern models a bad practice (unread side effects on static state).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions