Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
bump: patch
---

### Changed

- **`/tdd:principles` anti-patterns and testable-architecture pages carry no C# listings.** `anti-patterns-khorikov.md` loses its eleven C#, Moq (`CallBase`) and `DateTime.Now` listings, and `testable-architecture-khorikov.md` loses its six C#, xUnit.net and Fluent Assertions listings (the CRM refactoring, the domain-layer test, CanExecute/Execute and domain events). Where a listing carried the only statement of a point (the code-pollution flag and its interface fix, partial mocking of a concrete class, time as ambient context, the two ways to inject time, when domain events are recorded and sent), the point is now stated in prose. The rules both pages teach are unchanged ([#17767](https://github.com/melodic-software/claude-code-plugins/issues/17767)).
2 changes: 0 additions & 2 deletions .performance/ratchets.json
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,6 @@
"plugins/playwright/skills/demo-video/reference/replay-script.md": 1,
"plugins/playwright/skills/playwright/reference/running-code.md": 3,
"plugins/playwright/skills/playwright/reference/test-generation.md": 2,
"plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md": 11,
"plugins/tdd/skills/principles/reference/testable-architecture-khorikov.md": 6,
"plugins/user-interface/skills/write-css/reference/foundations.md": 6,
"plugins/user-interface/skills/write-css/reference/interaction.md": 14,
"plugins/user-interface/skills/write-css/reference/layout.md": 8,
Expand Down
196 changes: 12 additions & 184 deletions plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,50 +17,12 @@ If the observable behavior doesn't provide sufficient coverage for a complex pri
1. **Dead code**: the private method contains unused logic left after a refactoring. Delete it
2. **Missing abstraction**: the private method contains important logic that deserves its own class

```csharp
// BEFORE — complex private method buried inside Order
public class Order
{
public string GenerateDescription() { /* uses GetPrice() */ }
private decimal GetPrice() { /* complex: base, discounts, taxes */ }
}

// AFTER — extract the missing abstraction
public class PriceCalculator
{
public decimal Calculate(Customer customer, List<Product> products)
{
decimal basePrice = /* ... */;
decimal discounts = /* ... */;
decimal taxes = /* ... */;
return basePrice - discounts + taxes;
}
}
```

`PriceCalculator` is now a public class with a public method, testable with output-based testing. No hidden inputs or outputs.
Extract that logic into its own class (for example, price calculation pulled out of an order, taking the customer and products as explicit inputs). It is then reachable through a public method, testable with output-based testing. No hidden inputs or outputs.

### The Rare Exception: Private Methods That Are Observable Behavior

In rare cases, a private method is both private AND part of observable behavior. Example: a class with a private constructor used by an ORM to restore objects from the database.

```csharp
public class Inquiry
{
public bool IsApproved { get; private set; }
public DateTime? TimeApproved { get; private set; }

private Inquiry(bool isApproved, DateTime? timeApproved)
{
if (isApproved && !timeApproved.HasValue)
throw new Exception();
// ...
}

public void Approve(DateTime now) { /* ... */ }
}
```

The private constructor fulfills the ORM contract. It's observable behavior from the ORM's perspective. Making it public (with proper preconditions) won't lead to test brittleness and arguably improves the API design. Alternative: use reflection to instantiate in tests (mirrors what the ORM does).

## 2. Exposing Private State for Testing
Expand All @@ -69,57 +31,19 @@ The private constructor fulfills the ORM contract. It's observable behavior from

Don't expose private fields/properties just to assert on them. Instead, test through what the production code actually observes.

```csharp
public class Customer
{
private CustomerStatus _status = CustomerStatus.Regular;

public void Promote() { _status = CustomerStatus.Preferred; }
public decimal GetDiscount()
{
return _status == CustomerStatus.Preferred ? 0.05m : 0m;
}
}
```

Don't make `_status` public for testing. The production code uses `GetDiscount()`, so test through that:
Example: a customer whose private status field decides its discount. Don't make the status field public for testing. The production code reads the discount, so test through that:

- A newly created customer has no discount (0%)
- Once promoted, the discount becomes 5%

If the production code later starts using `_status` directly, it would naturally become part of the observable behavior and should then be public.
If the production code later starts using the status directly, it would naturally become part of the observable behavior and should then be public.

> "Widening the public API surface for the sake of testability is a bad practice."

## 3. Leaking Domain Knowledge to Tests

Tests that reproduce the production algorithm in the arrange section are **tautology tests**. They couple to implementation details and have near-zero resistance to refactoring.

```csharp
// BAD — leaking the algorithm into the test
[Theory]
[InlineData(1, 3)]
[InlineData(11, 33)]
[InlineData(100, 500)]
public void Adding_two_numbers(int value1, int value2)
{
int expected = value1 + value2; // ← THE LEAKAGE
int actual = Calculator.Add(value1, value2);
Assert.Equal(expected, actual);
}

// GOOD — hardcoded expected values, no algorithm duplication
[Theory]
[InlineData(1, 3, 4)]
[InlineData(11, 33, 44)]
[InlineData(100, 500, 600)]
public void Adding_two_numbers(int value1, int value2, int expected)
{
int actual = Calculator.Add(value1, value2);
Assert.Equal(expected, actual);
}
```

> **"Don't imply any specific implementation when writing tests."** Hardcode expected results. For complex algorithms, precalculate expected values with the help of a domain expert or (for legacy refactoring) use the old system's output as the expected baseline.

This may seem counterintuitive, but hardcoded values provide an independent checkpoint. Tests that duplicate the algorithm become a mirror. If the algorithm changes, developers copy-paste the new version into the test without investigating whether the change is correct.
Expand All @@ -128,84 +52,21 @@ This may seem counterintuitive, but hardcoded values provide an independent chec

> **Code pollution** is adding production code that's only needed for testing.

The classic form is a Boolean switch:

```csharp
// BAD — production code has test-only path
public class Logger
{
private readonly bool _isTestEnvironment;

public void Log(string text)
{
if (_isTestEnvironment) return; // ← code pollution
/* actual logging */
}
}
```
The classic form is a Boolean switch: a flag that makes production code skip its work under test.

Code pollution mixes test and production concerns, increasing maintenance costs. The test-only code path can be accidentally invoked in production.

**Fix**: introduce an interface with separate implementations:

```csharp
public interface ILogger
{
void Log(string text);
}

public class Logger : ILogger // Production
{
public void Log(string text) { /* actual logging */ }
}
**Fix**: introduce an interface with separate implementations, a real one for production and a fake one in test code only.

public class FakeLogger : ILogger // Test code only
{
public void Log(string text) { /* do nothing */ }
}
```

The `ILogger` interface is technically a mild form of code pollution (it exists partly for testing), but it's far less damaging. Interfaces have no code, can't harbor bugs, and can't accidentally trigger production behavior.
The interface is technically a mild form of code pollution (it exists partly for testing), but it's far less damaging. Interfaces have no code, can't harbor bugs, and can't accidentally trigger production behavior.

## 5. Mocking Concrete Classes

When a class combines domain logic with out-of-process communication, mocking it via `virtual` methods (using `CallBase = true`) is tempting but is an anti-pattern.

```csharp
// StatisticsCalculator mixes two responsibilities:
// 1. GetDeliveries() — calls external service (communication)
// 2. Calculate() — business logic

// Anti-pattern: mock the concrete class, override GetDeliveries only
var stub = new Mock<StatisticsCalculator> { CallBase = true };
stub.Setup(x => x.GetDeliveries(1))
.Returns(new List<DeliveryRecord>());
```
When a class combines domain logic with out-of-process communication, mocking it partially (overriding only the communication method while keeping the real domain logic) is tempting but is an anti-pattern.

> "The necessity to mock a concrete class in order to preserve part of its functionality is a result of violating the Single Responsibility principle."

**Fix**: split into two classes using the Humble Object pattern:

```csharp
// Communication responsibility → interface-backed gateway
public class DeliveryGateway : IDeliveryGateway
{
public List<DeliveryRecord> GetDeliveries(int customerId)
{
/* Call external service */
}
}

// Domain logic → pure calculator, no out-of-process deps
public class StatisticsCalculator
{
public (double totalWeight, double totalCost) Calculate(
List<DeliveryRecord> records)
{
/* Pure calculation */
}
}
```
**Fix**: split into two classes using the Humble Object pattern: an interface-backed gateway for the communication and a pure calculator, with no out-of-process dependencies, for the domain logic.

The controller orchestrates: calls the gateway, passes results to the calculator. The gateway gets mocked (unmanaged dependency); the calculator is tested directly (domain logic). No need to mock concrete classes.

Expand All @@ -215,51 +76,18 @@ Three approaches to stabilizing time in tests:

### Anti-Pattern: Time as Ambient Context

```csharp
// BAD — static mutable state, shared between tests
public static class DateTimeServer
{
private static Func<DateTime> _func;
public static DateTime Now => _func();

public static void Init(Func<DateTime> func) { _func = func; }
}

// Production: DateTimeServer.Init(() => DateTime.Now);
// Test: DateTimeServer.Init(() => new DateTime(2020, 1, 1));
```

This **pollutes** production code with test infrastructure, makes the dependency hidden, and introduces a shared static field that prevents test parallelization.
A static, mutable time provider that production initializes with the system clock and tests initialize with a fixed date **pollutes** production code with test infrastructure, makes the dependency hidden, and introduces a shared static field that prevents test parallelization.

### Good: Time as an Explicit Dependency

Two sub-options:

**As a service** (injected into the controller):

```csharp
public class InquiryController
{
private readonly DateTimeServer _dateTimeServer;

public void ApproveInquiry(int id)
{
Inquiry inquiry = GetById(id);
inquiry.Approve(_dateTimeServer.Now); // passes value to domain
SaveInquiry(inquiry);
}
}
```

**As a plain value** (passed directly to the domain method):

```csharp
inquiry.Approve(DateTime.Now); // caller provides the value
```
- **As a service**: the controller receives a time provider and passes its current value to the domain method.
- **As a plain value**: the caller passes the current time directly to the domain method.

> "Prefer injecting the time as a value rather than as a service. It's easier to work with plain values in production code, and it's also easier to stub those values in tests."

**Khorikov's recommended compromise**: inject time as a service at the controller level (DI-friendly), then pass it as a plain value to domain classes. The controller in listing 11.17 does exactly this. It accepts `DateTimeServer` (service) but passes `_dateTimeServer.Now` (value) to `inquiry.Approve()`.
**Khorikov's recommended compromise**: inject time as a service at the controller level (DI-friendly), then pass it as a plain value to domain classes.

## Quick Reference

Expand Down
Loading
Loading