diff --git a/.changes/tdd/work-resolve-issue-issue-17767-44944165148-1-1162669f.md b/.changes/tdd/work-resolve-issue-issue-17767-44944165148-1-1162669f.md new file mode 100644 index 0000000000..0fbaa8e9a2 --- /dev/null +++ b/.changes/tdd/work-resolve-issue-issue-17767-44944165148-1-1162669f.md @@ -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)). diff --git a/.performance/ratchets.json b/.performance/ratchets.json index 71eacf4081..6c54bc3c18 100644 --- a/.performance/ratchets.json +++ b/.performance/ratchets.json @@ -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, diff --git a/plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md b/plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md index 1ed269ab01..39b9622043 100644 --- a/plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md +++ b/plugins/tdd/skills/principles/reference/anti-patterns-khorikov.md @@ -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 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 @@ -69,25 +31,12 @@ 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." @@ -95,31 +44,6 @@ If the production code later starts using `_status` directly, it would naturally 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. @@ -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 { CallBase = true }; -stub.Setup(x => x.GetDeliveries(1)) - .Returns(new List()); -``` +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 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 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. @@ -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 _func; - public static DateTime Now => _func(); - - public static void Init(Func 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 diff --git a/plugins/tdd/skills/principles/reference/testable-architecture-khorikov.md b/plugins/tdd/skills/principles/reference/testable-architecture-khorikov.md index bf63a46d10..b8d5f2090a 100644 --- a/plugins/tdd/skills/principles/reference/testable-architecture-khorikov.md +++ b/plugins/tdd/skills/principles/reference/testable-architecture-khorikov.md @@ -59,17 +59,6 @@ A CRM system with a `User.ChangeEmail()` method demonstrates progressive refacto `User` directly calls `Database` and `MessageBus`, both static out-of-process dependencies. High domain significance (email change logic) AND high collaborator count (database + message bus). Falls in the overcomplicated quadrant. -```csharp -// BEFORE — overcomplicated: business logic + out-of-process deps mixed -public void ChangeEmail(int userId, string newEmail) -{ - object[] data = Database.GetUserById(userId); - // ... business logic interleaved with Database and MessageBus calls ... - Database.SaveUser(this); - MessageBus.SendEmailChangedMessage(UserId, newEmail); -} -``` - ### Take 1: Make Implicit Dependencies Explicit Introduce interfaces for `Database` and `MessageBus`, inject them. **Not enough**. From the types-of-code perspective, interfaces behind out-of-process dependencies are still out-of-process. Tests still need complicated mock machinery. @@ -80,7 +69,7 @@ Introduce interfaces for `Database` and `MessageBus`, inject them. **Not enough* Move all out-of-process communication to a `UserController` (application service). `User` no longer touches `Database` or `MessageBus`. With zero collaborators, it moves to the domain model quadrant. -**Problem**: the controller now contains reconstruction logic (mapping raw `object[]` data to domain objects) and returns the updated employee count from `User.ChangeEmail()`, a misplaced responsibility. +**Problem**: the controller now contains reconstruction logic (mapping raw database rows to domain objects) and returns the updated employee count from `User.ChangeEmail()`, a misplaced responsibility. ### Take 3: Remove Complexity from the Application Service @@ -90,48 +79,6 @@ Extract reconstruction logic into `UserFactory` and `CompanyFactory`. The contro The awkwardness of returning an updated number of employees reveals a missing abstraction. Introduce `Company` as a domain class with `ChangeNumberOfEmployees()` and `IsEmailCorporate()` methods. -```csharp -// AFTER — clean separation -public class User -{ - public void ChangeEmail(string newEmail, Company company) - { - if (Email == newEmail) return; - - UserType newType = company.IsEmailCorporate(newEmail) - ? UserType.Employee : UserType.Customer; - - if (Type != newType) - { - int delta = newType == UserType.Employee ? 1 : -1; - company.ChangeNumberOfEmployees(delta); - } - - Email = newEmail; - Type = newType; - } -} - -// Controller — pure orchestration, no business logic -public class UserController -{ - public void ChangeEmail(int userId, string newEmail) - { - object[] userData = _database.GetUserById(userId); - User user = UserFactory.Create(userData); - - object[] companyData = _database.GetCompany(); - Company company = CompanyFactory.Create(companyData); - - user.ChangeEmail(newEmail, company); - - _database.SaveCompany(company); - _database.SaveUser(user); - _messageBus.SendEmailChangedMessage(userId, newEmail); - } -} -``` - `Company`'s methods follow the **Tell Don't Ask** principle. `User` *tells* `Company` to change its employee count rather than asking for raw data and doing it itself. ### Final Types-of-Code Placement @@ -145,22 +92,7 @@ public class UserController ### Domain Layer (Unit Test) -High-value, low-cost tests, output-based and state-based on in-memory objects: - -```csharp -[Fact] -public void Changing_email_from_non_corporate_to_corporate() -{ - var company = new Company("mycorp.com", 1); - var sut = new User(1, "user@gmail.com", UserType.Customer); - - sut.ChangeEmail("new@mycorp.com", company); - - Assert.Equal(2, company.NumberOfEmployees); - Assert.Equal("new@mycorp.com", sut.Email); - Assert.Equal(UserType.Employee, sut.Type); -} -``` +High-value, low-cost tests, output-based and state-based on in-memory objects. Four tests cover all branches. Parameterized tests work well for simpler classes like `Company.IsEmailCorporate`. @@ -170,7 +102,7 @@ Constructors with no logic. Tests would provide close-to-zero value. ### Preconditions -Test preconditions that have **domain significance** (e.g., `Company.ChangeNumberOfEmployees` requiring non-negative result). Don't test preconditions that are merely technical safeguards without domain meaning (e.g., `UserFactory.Create` requiring array length >= 3). +Test preconditions that have **domain significance** (e.g., `Company.ChangeNumberOfEmployees` requiring non-negative result). Don't test preconditions that are merely technical safeguards without domain meaning (e.g., `UserFactory.Create` requiring the raw row to have at least three fields). ### Controllers (Integration Test) @@ -209,27 +141,7 @@ When business logic needs intermediate data from out-of-process dependencies (ca Prevents business logic from leaking into controllers when splitting decisions into steps. The domain model exposes a `CanExecute` method that the controller calls first. The `Execute` method has a precondition requiring `CanExecute` to pass. -```csharp -// Domain model — all validation encapsulated -public string CanChangeEmail() -{ - if (IsEmailConfirmed) - return "Can't change a confirmed email"; - return null; -} - -public void ChangeEmail(string newEmail, Company company) -{ - Precondition.Requires(CanChangeEmail() == null); - // ... the rest of the method -} - -// Controller — no business knowledge needed -string error = user.CanChangeEmail(); -if (error != null) - return error; -// ... proceed with change -``` +In the CRM example, `User.CanChangeEmail()` returns the reason a change is refused (the email is already confirmed) or nothing; the controller returns that reason to its caller, and `ChangeEmail()` requires `CanChangeEmail()` to report nothing. Benefits: @@ -237,44 +149,13 @@ Benefits: - The precondition in `ChangeEmail()` guarantees the method is never called without validation - Multiple validations consolidate into the `CanExecute` method, extensible without touching the controller -> "For simplicity's sake, I'm using a `string` to denote an error. In a real-world project, you may want to introduce a custom `Result` class." - ## Domain Events Track important changes in the domain model and convert them to out-of-process calls *after* the business operation completes. Prevents the controller from needing to decide *when* to notify external systems. > **"A domain event describes an event in the application that is meaningful to domain experts."** Domain events should always be named in the past tense because they represent things that already happened. They are values: immutable and interchangeable. -```csharp -public class EmailChangedEvent -{ - public int UserId { get; } - public string NewEmail { get; } -} - -// User adds event only when email actually changes -public void ChangeEmail(string newEmail, Company company) -{ - Precondition.Requires(CanChangeEmail() == null); - if (Email == newEmail) return; - // ... business logic ... - EmailChangedEvents.Add( - new EmailChangedEvent(UserId, newEmail)); -} - -// Controller processes events after the fact -foreach (var ev in user.EmailChangedEvents) -{ - _messageBus.SendEmailChangedMessage(ev.UserId, ev.NewEmail); -} -``` - -This solves the notification bug (sending messages when email didn't change) by making the domain model responsible for *when* events are generated. Tests verify domain event creation directly, with no mocks needed: - -```csharp -sut.EmailChangedEvents.Should().Equal( - new EmailChangedEvent(1, "new@gmail.com")); -``` +`User` records an `EmailChangedEvent` only when the email actually changes, and the controller sends one message per recorded event after the business operation completes. This solves the notification bug (sending messages when email didn't change) by making the domain model responsible for *when* events are generated. Tests verify domain event creation directly, with no mocks needed. > "Domain events remove the decision-making responsibility from the controller and put that responsibility into the domain model, thus simplifying unit testing communications with external systems."