Practice ยท 3 of 3
Debug: The Generator That Remembers
This ReportGenerator broke in a code review โ reports leak across
instances, and fresh data stops appearing:
``csharp
public sealed class ReportGenerator // BROKEN โ do not ship this
{
private static readonly List<string> Cache = new(); // shared by ALL instances
private readonly IFetcher _fetcher;
public ReportGenerator(IFetcher fetcher) => _fetcher = fetcher;
public string[] Generate()
{
if (Cache.Count == 0)
foreach (var r in _fetcher.Fetch()) Cache.Add(...);
return Cache.ToArray();
}
}
`
Two sins: **static state shared by every instance**, and **caching input
data** the caller expects to be re-read. Write a correct ReportGenerator:
no state beyond the injected IFetcher, and Generate() reflects the
fetcher's *current* rows every call, formatted "1. row", "2. row" (1-based).
`csharp
public sealed class ReportGenerator { public ReportGenerator(IFetcher fetcher); public string[] Generate(); }
``
Back to lesson: Practice: Clean Code Practice: Guards, Totals, Reports