Strategy pattern
· Last updated: 2026-11-05 · 60 min read
The Strategy pattern is a behavioral pattern: it puts several algorithms that serve the same role behind a common contract, so the implementation in use can be swapped. The caller knows what work it hands over and what result to expect, while the selected implementation decides how that work is done. An algorithm here is not limited to complicated mathematical calculation. Everyday processing rules count too, such as how a string should be displayed or in what order products should be arranged. The trouble starts when one such rule has to differ from screen to screen.
One screen may need to display hello unchanged and another should display HELLO. Both screens follow the same process of receiving text and writing it out. Only the conversion rule changes. A function that returns the original text and a function that capitalizes it can fill the same position in that process. Only that one rule differs between the screens, and the rest of the flow needs no change. These are the two strategies in the first, deliberately small example below.
The calling code chooses a conversion rule. The output component calls it, receives a string, and writes that string to the screen. It has no need to know how capitalization works. What moves is the conversion; the code that receives the string and writes it out stays. Another conversion can occupy that position later if it keeps the same input and result contract, while the output process stays the same.
Pattern descriptions call the component using the strategy the Context, the shared contract the Strategy, and each implementation a Concrete Strategy. The code choosing an implementation and connecting it to the context acts as the Client. Once the split has names, it is easier to see which part of the code a change touches. You can follow who requests the work, who performs it, and where the choice happens before learning these names. A later table maps them to the diagnostic example.
For text conversion, the contract might be “receive one string and return a string.” For a diagnostic formatter, it becomes “receive a diagnostic containing an error location and message, and return a string representing it.” Readable text and JSON look different, but both represent the diagnostic. The reporter relies on that shared role when it calls either formatter. That promise holds still while implementations multiply.
Matching parameter and return types covers only part of the contract. Implementations also need compatible rules for valid inputs, the meaning of the result, and side effects such as changing input or writing files. If one formatter writes to a file and returns an empty string, the reporter receives no diagnostic text to display. The main examples start with the replacement structure; the appendices add input, result, and side-effect rules. Stating the permitted side effects next to the types keeps that mismatch from creeping in.
An interface declares the method's input and result contract, and each class implements that behavior. A function type or delegate can express the contract too. Other languages offer tools such as traits. Whatever the syntax, the component calls a single position. A function parameter is often convenient for a single operation; an object may fit better when each implementation holds configuration or resources. This article starts with a small function, develops a formatter built from classes, and then returns to functions and sorting.
Selection time is a separate decision. A CLI (a command-line program) can choose once when it reads its startup options, or a different rule can be connected for each request. A build can also fix the implementation, and a program that replaces a strategy during execution must decide when replacement is allowed and what happens to work already in progress. Settling the timing early also settles whether a replacement setter has any job. Reading that a strategy can be swapped does not mean every object needs a replacement setter.
Separating strategies helps when the same choice appears in several places or when processing rules need independent changes and tests. Discount calculations, sorting, compression, and diagnostic output are possible uses. Splitting a small conditional in one place, or a difference of a few values, into classes only adds code to read, so it is better to write down first, from the requirements, which rule changes and which contract must stay stable. With that in place, deciding whether one function or a separate object is enough can wait. The judgment comes from how often the rule changes and how many places repeat it, not from taste.
Plain returns its input unchanged; Upper converts it to uppercase. Print writes the result of whichever function it receives. Both functions simply take the same position. This small C# program runs on its own.
using System;
string Plain(string text) => text;
string Upper(string text) => text.ToUpperInvariant();
void Print(string text, Func<string, string> format) =>
Console.WriteLine(format(text));
Print("hello", Plain); // hello
Print("hello", Upper); // HELLOIn Print("hello", Plain), format refers to Plain. In the next call, it refers to Upper. The call to format(text) runs the supplied function, producing hello and HELLO respectively. Each call brings a different function; the component still does one thing.
Func<string, string> means a function that takes one string and returns a string. Writing Plain or Upper without parentheses passes the function itself. Writing Upper("hello") would run it immediately and produce its result. Because the types match, the component calls either function the same way.
If Print checks the format name and performs every conversion itself, adding a rule also means editing the printing code. When several screens or output paths repeat that choice, changing one rule means reviewing all those paths. Each new rule also lengthens that method, and testing it drags the output along.
Passing the conversion as a function lets the caller choose the rule. The printing code calls what it receives, and the conversion can be tested separately or reused with another output path. It no longer needs to know what the rule does.
This small example alone is not enough reason to build a separate strategy. If one place handles only two formats, a conditional is still easy to read. If you write down the requirements first and settle what actually needs to be swapped and what promise every implementation must share, it is easier to judge whether one function suffices or a separate object is needed. Adding a class to delete one small conditional is a bad trade.
In everyday terms, the main contractor sets the contract and the subcontractor does the implementation. What crosses over is what the contract names; how the work gets done stays on the other side. A good subcontractor does not need to know the main contractor's internal affairs. A good programmer is rather like a good subcontractor.
The first example takes a string and returns a string. A diagnostic formatter takes a Diagnostic, containing an error location and message, and returns readable text or JSON. The replaceable part is still the rule that turns the input into a string, and a formatter is what takes that job. The input changes shape, but the position where it is swapped stays the same.
Suppose we are building a compiler.
When the compiler finds an error in source code, it prints a diagnostic for the user.
main.pgy:12: E001: Name not found.JSON can be more convenient when a development tool or another program needs to process that diagnostic.
Who reads the output decides the format. A person can read the error sentence, but a program needs to extract the file name, line number, and error code separately. Named JSON fields make those values easier to distinguish than splitting and interpreting the sentence again.
A developer passing diagnostics to an AI tool may also prefer JSON fields to a sentence the tool has to interpret again.
For example, the same diagnostic can be represented as JSON as follows. The implementation's actual output also puts a schemaVersion field first, and because of the System.Text.Json default encoder, Hangul is escaped as \uXXXX.
{
"file": "main.pgy",
"line": 12,
"code": "E001",
"message": "Name not found."
}This role of converting the same data into a chosen representation is called a formatter.
The data here consists of the error location, code, and message. The formatter turns those values into a readable sentence or a JSON string another program can process.
The formatter builds a string. An output component writes it to a screen or a file, allowing the representation and destination to change independently.
Report(diagnostic, format, output)
├─ human → build human-readable text
└─ json → build a JSON string
↓
write to outputAs formats grow, the readable version may gain color and newline rules, while JSON may need new fields and a schema version. If file output and batch runs repeat the same format selection, changing one format means reviewing several paths. Small tasks tend to reveal these complications once you implement them.
Report() started with the job of writing a diagnostic, but now also manages every format's internal rules.
Give the formats a shared Format(diagnostic) contract, and move each representation out of the reporter into its own implementation.
If every formatter accepts a Diagnostic and returns a string, the reporter can call them all in the same way. This is the same arrangement as Print calling either Plain or Upper through format(text). Because the promise matches, the reporter calls without looking at the implementation.
The reporter calls the formatter it was given. Each formatter handles its own conversion rules.
To add a format, implement the common contract and connect it at the selection point. The reporter's output flow can stay as it is. Only the selection point changes.
Consider it when alternatives perform the same role and their implementations need to be explained or replaced independently. It earns its keep when that choice recurs.
Even in the examples below, a lookup table may suffice if only a few labels differ. Look at what actually changes rather than starting from the feature's name.
Use case | Replaceable part |
|---|---|
Diagnostics and reports | Human-readable text, JSON, or another output format |
Product sorting | Price order, newest first, or priority products |
Price calculation | Percentage discounts, fixed discounts, or other calculation rules |
Data compression | Compression methods that satisfy a common input and result contract |
Part of a retry policy | Calculating the delay from the attempt count |
Diagnostics and reports
Human-readable text, JSON, or another output format
Product sorting
Price order, newest first, or priority products
Price calculation
Percentage discounts, fixed discounts, or other calculation rules
Data compression
Compression methods that satisfy a common input and result contract
Part of a retry policy
Calculating the delay from the attempt count
Game damage calculations can use this structure too. The formulas vary by game, so consider Strategy when a game needs interchangeable calculation rules. A game with no single settled formula is worth a look.
The diagnostic-output example maps to the pattern's roles as follows.
Role | Name in this example | Responsibility |
|---|---|---|
Context |
| Requests formatting and writes the result |
Strategy |
| Defines the common contract for converting a diagnostic into a string |
Concrete Strategy |
| Implements the conversion for each format |
Client | Startup code or request-handling code | Chooses a format and connects the reporter to its strategy |
Context
DiagnosticReporter
Requests formatting and writes the result
Strategy
IDiagnosticFormatter
Defines the common contract for converting a diagnostic into a string
Concrete Strategy
HumanDiagnosticFormatter, JsonDiagnosticFormatter
Implements the conversion for each format
Client
Startup code or request-handling code
Chooses a format and connects the reporter to its strategy
Context is the code that uses the strategy; Concrete Strategy is the implementation that does the work. Client chooses the implementation and connects them. In this example, the program's startup code takes that role. The three names attach to the component, the rule, and the selection code seen earlier.
If format selection grows, it can go in a factory. Here, a factory takes a name such as human or json and creates the corresponding formatter, as shown in Appendix A.
Startup or request-handling code
-> validate the format name and select a formatter
-> pass the formatter to DiagnosticReporter
DiagnosticReporter.Report(diagnostic, output)
-> IDiagnosticFormatter.Format(diagnostic)
-> HumanDiagnosticFormatter or JsonDiagnosticFormatter
-> write the returned string to outputThe caller selects a formatter and passes it to DiagnosticReporter, so the reporter does not need to know the format names. A component can select its own strategy, too. Here, letting the assembly code make that choice makes it easier to change selection and execution rules independently.
Start with a valid, single-line diagnostic and concentrate on replacing the formatter. The three C# blocks in this section form one program when combined in order. It is the earlier function example rebuilt with objects. Appendix A adds input validation.
Diagnostic groups the file name, line number, error code, and message into one input value. IDiagnosticFormatter defines the position where a conversion can be supplied. Its string Format(Diagnostic diagnostic) signature asks for one diagnostic and returns one string, without choosing its format yet. The reporter knows only this contract, so a new format changes the argument of the constructor and nothing else.
using System;
using System.IO;
using System.Text.Json;
public sealed record Diagnostic(string File, int Line, string Code, string Message);
// The reporting context uses a shared data-to-text contract rather than a concrete format.
public interface IDiagnosticFormatter
{
string Format(Diagnostic diagnostic);
}These declarations produce no output by themselves. new Diagnostic("main.pgy", 12, "E001", "Name not found.") creates the input; the implementations below decide how to turn it into text. The parameter of Format receives that input, and the string return value supplies what the reporter will write.
HumanDiagnosticFormatter and JsonDiagnosticFormatter fill that position. The first joins the file name, line number, code, and message into readable text. The second places the same values in JSON fields. Both implement IDiagnosticFormatter, so the reporter can call either through the same method.
public sealed class HumanDiagnosticFormatter : IDiagnosticFormatter
{
public string Format(Diagnostic diagnostic) =>
$"{diagnostic.File}:{diagnostic.Line}: {diagnostic.Code}: {diagnostic.Message}";
}
public sealed class JsonDiagnosticFormatter : IDiagnosticFormatter
{
public string Format(Diagnostic diagnostic) =>
JsonSerializer.Serialize(new
{
schemaVersion = 1,
file = diagnostic.File,
line = diagnostic.Line,
code = diagnostic.Code,
message = diagnostic.Message
});
}The readable-text formatter turns that diagnostic into main.pgy:12: E001: Name not found.. The JSON formatter produces a string with schemaVersion and the fields file, line, code, and message. The diagnostic and calling convention stay the same while the representation changes.
DiagnosticReporter uses this contract. Its constructor receives a formatter and stores it in a field. Report passes the diagnostic to that formatter’s Format method, then writes the returned string through output.WriteLine. TextWriter is the type used for the output destination; this example supplies standard output through Console.Out.
new DiagnosticReporter(new HumanDiagnosticFormatter()) assembles a reporter with the readable-text rule. The JSON reporter is built in the same way. Both objects execute the same Report method; the formatter connected during construction determines the conversion.
Calling new HumanDiagnosticFormatter() inside the reporter would make the reporter choose that format. Passing a formatter from outside lets the caller choose JSON while keeping the reporter unchanged. This is dependency injection. The assembly code decides what can change; the caller uses only what it receives.
// Call the selected formatter instead of adding format-specific branches here.
public sealed class DiagnosticReporter
{
private readonly IDiagnosticFormatter formatter;
public DiagnosticReporter(IDiagnosticFormatter formatter) =>
this.formatter = formatter;
public void Report(Diagnostic diagnostic, TextWriter output) =>
output.WriteLine(formatter.Format(diagnostic));
}
public static class Program
{
public static void Main()
{
var diagnostic = new Diagnostic(
"main.pgy", 12, "E001", "Name not found.");
var human = new DiagnosticReporter(new HumanDiagnosticFormatter());
var json = new DiagnosticReporter(new JsonDiagnosticFormatter());
human.Report(diagnostic, Console.Out);
json.Report(diagnostic, Console.Out);
}
}Follow the final two calls. human.Report(diagnostic, Console.Out) calls the readable-text formatter’s Format method and writes the sentence. json.Report sends the same diagnostic to the JSON formatter and writes its JSON string. Formatter objects occupy the position previously filled by Plain and Upper; the surrounding process still calls a selected rule and writes its result.
The same C# formatter-replacement structure can be written in TypeScript. A formatter turns Diagnostic into text; DiagnosticReporter calls the selected formatter, allowing another format without changing the reporting flow. The formatter does the same work as in the C# example.
type Diagnostic = Readonly<{ file: string; line: number; code: string; message: string }>;
// The reporting context uses a shared data-to-text contract rather than a concrete format.
interface IDiagnosticFormatter { format(diagnostic: Diagnostic): string; }
class HumanDiagnosticFormatter implements IDiagnosticFormatter {
format(diagnostic: Diagnostic): string {
return diagnostic.file + ":" + diagnostic.line + ": " + diagnostic.code + ": " + diagnostic.message;
}
}
class JsonDiagnosticFormatter implements IDiagnosticFormatter {
format(diagnostic: Diagnostic): string { return JSON.stringify({
schemaVersion: 1,
file: diagnostic.file,
line: diagnostic.line,
code: diagnostic.code,
message: diagnostic.message,
}); }
}
// Call the selected formatter instead of adding format-specific branches here.
class DiagnosticReporter {
constructor(private readonly formatter: IDiagnosticFormatter) {}
report(diagnostic: Diagnostic): string { return this.formatter.format(diagnostic); }
}
const diagnostic: Diagnostic = Object.freeze({ file: "main.pgy", line: 12, code: "E001", message: "Name not found." });
console.log(new DiagnosticReporter(new HumanDiagnosticFormatter()).report(diagnostic));
console.log(new DiagnosticReporter(new JsonDiagnosticFormatter()).report(diagnostic));main.pgy:12: E001: Name not found.
{"schemaVersion":1,"file":"main.pgy","line":12,"code":"E001","message":"Name not found."}The constructor selects the formatter, so no runtime replacement setter is needed. This version’s report() returns text and the caller writes it with console.log, rather than passing a TextWriter as in C#. The same input produces the same readable format and JSON fields. The extended implementation below adds input validation.
This example stores the strategy supplied through the constructor in a readonly field.
For a CLI whose format stays fixed during the process, select it at startup. For a server where requests choose different formats, assemble the reporter with the appropriate strategy when handling each request.
A DI container creates and connects the objects a component needs. Dependency injection does not require one. Constructing an object with new and passing it to the component that needs it is enough.1
The GoF text also shows fixing a strategy through C++ template arguments. This static selection fits an algorithm chosen per build or deployment; provide runtime replacement only when it is a separate requirement.2
Selection time | Suitable situation | Question to check |
|---|---|---|
Build or compile time | The algorithm is fixed per deployment | Does changing strategy require rebuilding? |
Startup | CLI options or process settings stay fixed | Are configuration errors detected at startup? |
Start of a request or job | Formats or customer policies vary per request | Can selection or state leak between requests? |
During execution | An editor changes its tool or processing mode | Does work already in progress use the old strategy or the new one? |
Build or compile time
The algorithm is fixed per deployment
Does changing strategy require rebuilding?
Startup
CLI options or process settings stay fixed
Are configuration errors detected at startup?
Start of a request or job
Formats or customer policies vary per request
Can selection or state leak between requests?
During execution
An editor changes its tool or processing mode
Does work already in progress use the old strategy or the new one?
When runtime replacement is unnecessary, keep the strategy supplied through the constructor. An editor that needs replacement should define when a strategy may change during a running operation. readonly prevents reference reassignment, not changes to the strategy object's internal state.
A function parameter can be easier to read when the contract is one calculation and the strategies need no separate lifetime management.
In C#, use a delegate or Func<...>. Microsoft's documentation describes calling a method supplied by the caller without the calling code knowing the concrete implementation.3
A formatter can be passed as a function, just like Plain and Upper in the first example.
This program runs separately from the class example. Think of it as changing Print(text, format) to Report(item, format), with a Diagnostic as the input instead of a string.
Func<Diagnostic, string> is a function type that takes a diagnostic and returns a string. In Report(diagnostic, Human), format refers to Human; in Report(diagnostic, Json), it refers to Json. The call to format(item) inside Report runs the one function supplied for that call.
using System;
using System.Text.Json;
var diagnostic = new Diagnostic("main.pgy", 12, "E001", "Name not found.");
string Human(Diagnostic item) =>
$"{item.File}:{item.Line}: {item.Code}: {item.Message}";
string Json(Diagnostic item) => JsonSerializer.Serialize(new
{
schemaVersion = 1,
file = item.File,
line = item.Line,
code = item.Code,
message = item.Message
});
void Report(Diagnostic item, Func<Diagnostic, string> format) =>
Console.WriteLine(format(item));
Report(diagnostic, Human);
Report(diagnostic, Json);
public sealed record Diagnostic(string File, int Line, string Code, string Message);In the first call, diagnostic becomes item, and the Human function becomes format. The expression format(item) therefore executes Human(diagnostic) for that call. In the second call, the supplied function is Json, so it executes Json(diagnostic). Each call runs the one formatter it receives.
The object's formatter.Format(diagnostic) has become format(diagnostic). This is shorter when there is no per-instance configuration or resource to hold. Appendix B applies it to several diagnostics together.
C# makes this possible by converting the method group to a compatible delegate value.
LINQ provides C# operations for querying and sorting collections. Here, supplying the ordering as a function lets us change the sorting rule while keeping the same list and output flow. Sorting is the standard case: one rule differs and everything else stays.
Start with three numbers before adding products and prices. The first Print accepted a text-conversion function. This Print accepts a function that orders a sequence of numbers. Both calls receive the same [3, 1, 2]; the rule chooses ascending or descending order. Run this program separately from the other examples.
using System;
using System.Collections.Generic;
using System.Linq;
var numbers = new[] { 3, 1, 2 };
IEnumerable<int> Ascending(IEnumerable<int> items) =>
items.OrderBy(number => number);
IEnumerable<int> Descending(IEnumerable<int> items) =>
items.OrderByDescending(number => number);
void Print(Func<IEnumerable<int>, IEnumerable<int>> order) =>
Console.WriteLine(string.Join(",", order(numbers)));
Print(Ascending); // 1,2,3
Print(Descending); // 3,2,1
Console.WriteLine(string.Join(",", numbers)); // 3,1,2In Print(Ascending), order refers to Ascending. Calling order(numbers) produces the ascending sequence, which string.Join joins with commas for display. Passing Descending in the next call gives 3,2,1. The final output is 3,1,2 because these ordering operations leave the original array unchanged.
Replacing numbers with products keeps the same call flow. This time some prices tie, so order by price first and use the smaller ID as the tie-breaker. The following standalone program assumes a valid product list.
IEnumerable<Product> is a sequence of products, and IOrderedEnumerable<Product> is a product sequence with ordering applied. Read Func<IEnumerable<Product>, IOrderedEnumerable<Product>> as “a function that receives a product sequence and returns an ordered product sequence.” That is the kind of function passed into the order parameter of Print.
using System;
using System.Collections.Generic;
using System.Linq;
var products = new[]
{
new Product(3, 2000m),
new Product(2, 1000m),
new Product(1, 1000m)
};
Func<IEnumerable<Product>, IOrderedEnumerable<Product>> cheapestFirst =
items => items.OrderBy(item => item.PriceWon).ThenBy(item => item.Id);
Func<IEnumerable<Product>, IOrderedEnumerable<Product>> expensiveFirst =
items => items.OrderByDescending(item => item.PriceWon).ThenBy(item => item.Id);
void Print(Func<IEnumerable<Product>, IOrderedEnumerable<Product>> order) =>
Console.WriteLine(string.Join(",", order(products).Select(item => item.Id)));
Print(cheapestFirst); // 1,2,3
Print(expensiveFirst); // 3,1,2
Console.WriteLine(string.Join(",", products.Select(item => item.Id))); // 3,2,1
public sealed record Product(int Id, decimal PriceWon);The input IDs are 3, 2, 1. Print(cheapestFirst) puts the two 1,000-won products first, orders those tied products by ID as 1, 2, and places the 2,000-won product 3 last. That gives 1,2,3. Descending price puts 3 first and still orders the tied products by ID, giving 3,1,2. The last line shows that the original order remains 3,2,1.
The two functions return the same elements in different orders, and the caller sorts with the function it receives. Use ThenBy to compare IDs when prices tie; another OrderBy establishes a new primary sort key. Appendix B extends the example.4
In TypeScript, start with a function that compares two numbers. This standalone example orders the same [3, 1, 2] in both directions. The surrounding sorted function follows the same steps for both calls.
const numbers = [3, 1, 2];
const ascending = (left: number, right: number): number => left - right;
const descending = (left: number, right: number): number => right - left;
function sorted(
values: readonly number[],
compare: (left: number, right: number) => number,
): number[] {
return [...values].sort(compare);
}
console.log(sorted(numbers, ascending)); // [1, 2, 3]
console.log(sorted(numbers, descending)); // [3, 2, 1]
console.log(numbers); // [3, 1, 2]ascending(3, 1) returns 2, which puts 3 after 1. ascending(1, 2) returns -1, which puts 1 before 2. A result of 0 treats the values as tied. Reversing the subtraction in descending reverses the order. The sorting operation decides when to compare values; each comparison uses the supplied rule.
In sorted(numbers, ascending), compare receives the function itself. [...values] makes a new array, and sort(compare) orders that copy. The result is [1, 2, 3], while numbers remains [3, 1, 2]. As in Print("hello", Upper), the caller supplies the rule to use.
Apply the same comparison idea to products. The LINQ example supplies a function that orders a whole sequence; this version supplies the rule that sort uses to compare two products. It assumes valid safe-integer prices and IDs. Appendix B includes input validation.
ProductComparison is a function type that receives two products and returns a number. The ascending rule computes left.priceWon - right.priceWon. When the prices tie and that result is 0, the expression uses left.id - right.id on the right of ||. The descending rule reverses the price subtraction and keeps the same ID tie-breaker.
type Product = Readonly<{ id: number; priceWon: number }>;
type ProductComparison = (left: Product, right: Product) => number;
// A comparison leaves inputs unchanged and expresses order with a negative value, zero, or a positive value.
const byPriceAscending: ProductComparison = (left, right) =>
left.priceWon - right.priceWon || left.id - right.id;
const byPriceDescending: ProductComparison = (left, right) =>
right.priceWon - left.priceWon || left.id - right.id;
function sortProducts(
products: readonly Product[],
compare: ProductComparison,
): Product[] {
// sort mutates the array, so copy the array before sorting.
// The product objects themselves are not deep-copied.
return [...products].sort(compare);
}
const products: readonly Product[] = [
{ id: 3, priceWon: 2000 },
{ id: 2, priceWon: 1000 },
{ id: 1, priceWon: 1000 },
];
const cheapFirst = sortProducts(products, byPriceAscending);
const expensiveFirst = sortProducts(products, byPriceDescending);
console.log(cheapFirst.map((product) => product.id)); // [1, 2, 3]
console.log(expensiveFirst.map((product) => product.id)); // [3, 1, 2]
console.log(products.map((product) => product.id)); // [3, 2, 1]Comparing product 3 at 2,000 won with product 2 at 1,000 won in ascending order gives a positive 2000 - 1000, so product 3 goes after product 2. Products 2 and 1 have no price difference, so subtracting their IDs puts product 1 first. The full ascending result is [1, 2, 3], and descending price gives [3, 1, 2]. Both calls to sortProducts copy the array and sort it with the supplied comparison.
Both strategies put the smaller ID first when prices tie, so their tie-breaking rule is the same. The array is copied, but the product objects inside it are not deep-copied. Even this minimal example requires a comparison function that leaves its inputs unchanged and defines a consistent order.5
Checking that a formatter produces the right string is different from checking that the program selected the right formatter. The two fail in different places.
Even a thoroughly tested JSON implementation gives the wrong output if "json" is accidentally connected to the human-readable formatter. Test the implementations and the selection code. Keep both checks side by side.
What to verify | Example check |
|---|---|
Input contract | Reject nonpositive line numbers, empty messages, and CR/LF in file names |
Common contract | Return a nonempty, single-line string and the same result for the same input |
Format-specific meaning | Keep the human-readable location correct and preserve JSON fields and the original message |
Selection boundary | Connect |
Reporter output | Write one line separator after the string and leave the caller-owned writer open |
Failure propagation | Reject contract violations and expose failures of the output device |
Input contract
Reject nonpositive line numbers, empty messages, and CR/LF in file names
Common contract
Return a nonempty, single-line string and the same result for the same input
Format-specific meaning
Keep the human-readable location correct and preserve JSON fields and the original message
Selection boundary
Connect human and json correctly and reject unknown names
Reporter output
Write one line separator after the string and leave the caller-owned writer open
Failure propagation
Reject contract violations and expose failures of the output device
Appendix C contains executable tests for the implementations and their selection.
Passing an object or function can look similar even when the reason for separating it is different.
More programming experience means seeing more detail. As a beginner, you might use pattern Z whenever situation C appears. With experience, you have more options for C, and may notice that C is really a combination of A and B that can be separated further.
Replacing a formatter, wrapping it to add a heading, and storing an output request to run later can produce similar-looking code, but serve different purposes.
Similar concept | Example | Distinction from Strategy |
|---|---|---|
State pattern | Delegate cancellation and dispatch to the current order-state object | Represent state-specific behavior and transitions, beyond a state value |
Template Method | Override a particular stage of an import operation | Use the parent's execution skeleton and stable inheritance hooks |
Command | Queue an output request for later execution | Store the request to execute rather than an alternative algorithm |
Adapter | Adapt an external library's API to the internal formatter contract | Make calling conventions and data representations compatible |
Decorator | Wrap an existing formatter to add a heading | Add functionality while retaining the existing behavior |
DI and composition | Supply a formatter to the component and delegate conversion to it | Describe dependency assembly, with a different intent and scope from algorithm replacement |
Function composition and pipelines | Read, parse, validate, and save in sequence | Execute several stages rather than choose one alternative |
Configuration and lookup tables | Keep the calculation while varying a rate or name | Different values alone do not require more strategy classes |
State pattern
Delegate cancellation and dispatch to the current order-state object
Represent state-specific behavior and transitions, beyond a state value
Template Method
Override a particular stage of an import operation
Use the parent's execution skeleton and stable inheritance hooks
Command
Queue an output request for later execution
Store the request to execute rather than an alternative algorithm
Adapter
Adapt an external library's API to the internal formatter contract
Make calling conventions and data representations compatible
Decorator
Wrap an existing formatter to add a heading
Add functionality while retaining the existing behavior
DI and composition
Supply a formatter to the component and delegate conversion to it
Describe dependency assembly, with a different intent and scope from algorithm replacement
Function composition and pipelines
Read, parse, validate, and save in sequence
Execute several stages rather than choose one alternative
Configuration and lookup tables
Keep the calculation while varying a rate or name
Different values alone do not require more strategy classes
In programming, state is current information that affects later behavior. It can be stored in variables or fields, such as a login-failure count or an order's Paid value. The State pattern is a particular design within that broad idea: separate state-specific behavior and delegate to the implementation of the current state.
Term | Meaning |
|---|---|
State value | Stored information such as the current failure count, order status, or edited content |
State machine | A model of transitions and behavior determined by states and events |
State pattern | A design that separates state-specific behavior into objects or similar units and delegates to the current state's implementation |
State value
Stored information such as the current failure count, order status, or edited content
State machine
A model of transitions and behavior determined by states and events
State pattern
A design that separates state-specific behavior into objects or similar units and delegates to the current state's implementation
A state machine can use enum + switch or a transition table. When the component delegates behavior to an implementation for its current state, the design can fit the GoF State pattern. People sometimes use state and State pattern interchangeably, though they refer to different things.6
An order moving through Awaiting payment -> Paid -> Shipping describes a state model. When cancellation, dispatch, and other operations contain scattered state-specific branches, there is a reason to consider grouping that behavior in PendingState, PaidState, and ShippedState and delegating to the current state object. A transition function or table may be enough if the transition rules are simple to inspect.
The shortcut "Strategy changes from outside; State changes from inside" does answer many simple questions. It becomes confusing when an external event changes state or a component selects its strategy automatically. Ask whether the design represents alternative algorithms for the same role or the object's state and transitions, rather than judging only by who makes the change.
For the document-review example, see State Pattern. For the broader concept and its history, see State.
In Template Method, a parent method calls an overridden hook on this; in Strategy, the component calls a collaborating object or function. An import operation can expose a stable sequence through inheritance hooks while receiving its parsing algorithm as a strategy, so the patterns can be combined. Inheritance can be used to control execution order, but it is not required for that purpose.
A decorator wrapped around the chosen formatter must still satisfy the output contract. Prepending a heading to a JSON document keeps the return type string but breaks JSON parsing. Adding functionality and keeping the result readable by existing consumers are separate questions. A decorator that preserves the contract can itself act as a strategy, and an adapter that fits an external API to the internal contract can be selected as one strategy among others.
Choosing a CSV parser or a JSON parser can be described as strategy selection. A flow that reads, parses, validates, and saves needs input and output contracts and failure or stopping rules for each stage. Those stages can have different types; they do not need to be forced through one interface.
Passing a formatter through a constructor is DI; assembling an object with another object and delegating conversion is composition. What makes this example Strategy is that the supplied implementations are alternatives for the same role and can be replaced while honoring their common contract.
Strategy fits choosing one alternative for a role. When several discount rules must all apply, the code combining them also needs rules for their order and whether they can be stacked. Choosing one alternative and combining several are different problems.
Suppose the list price is 10,000 won and both a 10% discount and a 1,000-won discount apply. Taking the percentage off first gives 8,000 won; taking the fixed amount off first gives 8,100 won. Even if both implementations satisfy IDiscountPolicy, the discount domain must decide which calculation is intended.
Define the discount base, application order, stacking rules, and rounding point as domain rules. One composite strategy or a separate discount pipeline can implement them. Creating a class for every possible combination, such as KoreaGoldMemberHolidayDiscountStrategy, tangles the changing dimensions together again.
If every country uses the same calculation and only the tax rate differs, passing rate data to one strategy or using a table may suffice. Distinguishing a value change from an algorithm change keeps class counts from growing unnecessarily.
Naming classes before working through the requirement can make the same code look like Strategy or State.
Write one sentence about what the requirement changes. "Change the transmission method" and "store a transmission request to execute later" describe different changes from the outset.
For notifications, what we separate depends on which behavior needs to change.
Added requirement | Design choice |
|---|---|
Send the same delivery request by email or another channel | Consider Strategy if the channels can share a delivery contract |
Keep the channel and add elapsed-time measurement around delivery | Consider a Decorator around the existing delivery operation |
The external SDK's delivery function and response do not match the internal contract | Use an Adapter to translate the difference |
Store the request and send it at a scheduled time | Separate request data from the executor, or express it as a Command |
Display waiting, processing, and completed delivery states | Start with a state value; a status display alone does not call for the State pattern |
Cancellation, resumption, other behavior, and stored data differ substantially by state | Consider whether the State pattern helps group state-specific responsibilities |
Send the same delivery request by email or another channel
Consider Strategy if the channels can share a delivery contract
Keep the channel and add elapsed-time measurement around delivery
Consider a Decorator around the existing delivery operation
The external SDK's delivery function and response do not match the internal contract
Use an Adapter to translate the difference
Store the request and send it at a scheduled time
Separate request data from the executor, or express it as a Command
Display waiting, processing, and completed delivery states
Start with a state value; a status display alone does not call for the State pattern
Cancellation, resumption, other behavior, and stored data differ substantially by state
Consider whether the State pattern helps group state-specific responsibilities
When these requirements coexist, an executor can take a scheduled request, select a channel strategy, and let that strategy use an adapter for the external SDK.
State-specific labels can stay in a lookup table, rate differences in configuration, and a small branch used in one place in a conditional. If one validation function makes state transitions readable and sufficiently testable, separate classes for every state are unnecessary.
A library that accepts user-supplied algorithms can justify a contract even with one built-in implementation. Without a replacement requirement, adding only DefaultStrategy may just add declarations and assembly code. Start with what actually needs to vary.
The GoF book Design Patterns describes Strategy as encapsulating a family of related algorithms so they can be interchanged. It also gives Policy as another name for the pattern.2
The publisher's record for Design Patterns gives October 31, 1994 as the publication date and 1995 as the copyright year.7 This dates the book's account of designs already in use, with names and collaboration structures.
The book's Strategy example separates line-breaking algorithms from the document-layout object. It keeps the layout object while replacing algorithms that work line by line or consider an entire paragraph. The intent is the same separation now often explained through discounts or sorting rules.2
In a 2009 retrospective interview, Ralph Johnson explained that some patterns may become unnecessary when a language offers other ways to solve the same problem, and that the GoF patterns are not intended for every language.8 A replacement point expressed with C# interfaces and classes can be a function parameter in TypeScript or Python. Use the form that makes the role and contract clear in the language at hand.
This extends the object example with input validation, output contracts, and format selection. It reuses the same type names, so keep it separate from the minimal version. Combine the C# blocks in Appendices A through C in order to form one program.
This method selects the format and builds its string in one place.
Here the format string controls both selection and conversion. Two jobs under one name also make changing either one harder. The "human" branch builds readable text, while the "json" branch builds JSON. Compare the results for the same diagnostic in this version and the strategy implementation below. In the strategy version, each formatter implements its format-specific conversion, and the reporter calls the formatter it receives.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
public sealed class BranchingDiagnosticReporter
{
public void Report(Diagnostic diagnostic, string format, TextWriter output)
{
ArgumentNullException.ThrowIfNull(diagnostic);
ArgumentNullException.ThrowIfNull(format);
ArgumentNullException.ThrowIfNull(output);
string rendered;
switch (format)
{
case "human":
var line = diagnostic.Line.ToString(CultureInfo.InvariantCulture);
var message = diagnostic.Message.Replace("\r", "\\r").Replace("\n", "\\n");
rendered = $"{diagnostic.File}:{line}: {diagnostic.Code}: {message}";
break;
case "json":
rendered = JsonSerializer.Serialize(new
{
schemaVersion = 1,
file = diagnostic.File,
line = diagnostic.Line,
code = diagnostic.Code,
message = diagnostic.Message
});
break;
default:
throw new ArgumentException("Unsupported output format.", nameof(format));
}
output.WriteLine(rendered);
}
}Two implementations can share the signature string Format(Diagnostic diagnostic) yet behave differently from the caller's perspective if one returns output text and another creates a file and returns its path. Replaceable implementations must agree on the meaning of the result and the permitted side effects, as well as the return type.
A formatter accepts one diagnostic and returns a nonempty string. The same input and fixed configuration produce the same result. It writes no output, leaves the input unchanged, and returns no actual CR or LF characters. The human-readable format displays message line breaks as \r and \n; the JSON serializer escapes them.
Diagnostic holds a file name, positive line number, diagnostic code, and message. The file name, code, and message all reject null, empty strings, and whitespace-only strings. File names and codes also reject CR/LF; a message with content may span several lines.
Follow one valid diagnostic from the Diagnostic constructor to Format first. Then trace where a zero line number or a file name containing a newline is rejected. The constructor checks the input conditions; the reporter shown later checks the returned string. These checks define what the reporter can rely on after a formatter is replaced.
public sealed class Diagnostic
{
public string File { get; }
public int Line { get; }
public string Code { get; }
public string Message { get; }
public Diagnostic(string file, int line, string code, string message)
{
File = RequireSingleLine(file, nameof(file));
Code = RequireSingleLine(code, nameof(code));
if (line <= 0)
throw new ArgumentOutOfRangeException(nameof(line));
if (string.IsNullOrWhiteSpace(message))
throw new ArgumentException("A diagnostic message is required.", nameof(message));
Line = line;
Message = message;
}
private static string RequireSingleLine(string value, string parameterName)
{
if (string.IsNullOrWhiteSpace(value) || value.Contains('\r') || value.Contains('\n'))
throw new ArgumentException("A nonempty single-line value is required.", parameterName);
return value;
}
}
// The reporting context uses a shared data-to-text contract rather than a concrete format.
public interface IDiagnosticFormatter
{
// Convert strings only; do not write output or mutate input.
// Return the same result for the same input and fixed configuration.
// The result must be nonempty and contain no actual CR/LF.
string Format(Diagnostic diagnostic);
}Invalid arguments raise argument-related exceptions; a formatter's output-contract violation raises InvalidOperationException. An output device's IOException also reaches the caller.
Human-readable text and JSON have different syntax even for the same diagnostic. They remain interchangeable here because both honor the common promise: return a nonempty string without actual CR/LF, and leave writing to the reporter.
These formatters add input checks and message-newline handling to the main example. The readable-text formatter escapes message newlines for display; JSON serialization handles them in the JSON version. Follow the same diagnostic into both implementations and check how each preserves the original message’s meaning.
public sealed class HumanDiagnosticFormatter : IDiagnosticFormatter
{
public string Format(Diagnostic diagnostic)
{
ArgumentNullException.ThrowIfNull(diagnostic);
var line = diagnostic.Line.ToString(CultureInfo.InvariantCulture);
var message = diagnostic.Message
.Replace("\r", "\\r")
.Replace("\n", "\\n");
return $"{diagnostic.File}:{line}: {diagnostic.Code}: {message}";
}
}
public sealed class JsonDiagnosticFormatter : IDiagnosticFormatter
{
public string Format(Diagnostic diagnostic)
{
ArgumentNullException.ThrowIfNull(diagnostic);
// Do not build JSON by concatenating strings.
// Let the serializer escape quotes and line breaks.
return JsonSerializer.Serialize(new
{
schemaVersion = 1,
file = diagnostic.File,
line = diagnostic.Line,
code = diagnostic.Code,
message = diagnostic.Message
});
}
}System.Text.Json produces JSON with message line breaks escaped inside strings. schemaVersion and the field names belong to this example's format.9
DiagnosticReporter writes the formatter's returned string without identifying the format. The output device is supplied externally too, so a test can use StringWriter while the real program uses a file or standard error.
The call flow is unchanged. Report checks the diagnostic, calls the selected formatter once, checks the returned string, and writes it. Changing Console.Out to StringWriter leaves formatter selection alone. Choosing the JSON formatter leaves writer handling alone.
// Call the selected formatter instead of adding format-specific branches here.
public sealed class DiagnosticReporter
{
private readonly IDiagnosticFormatter formatter;
public DiagnosticReporter(IDiagnosticFormatter formatter)
{
ArgumentNullException.ThrowIfNull(formatter);
this.formatter = formatter;
}
public void Report(Diagnostic diagnostic, TextWriter output)
{
ArgumentNullException.ThrowIfNull(diagnostic);
ArgumentNullException.ThrowIfNull(output);
var rendered = formatter.Format(diagnostic);
// Implementing an interface alone does not enforce behavioral contracts.
// Check the output shape that the reporter can verify immediately.
if (string.IsNullOrEmpty(rendered) || rendered.Contains('\r') || rendered.Contains('\n'))
throw new InvalidOperationException("The formatter violated the nonempty, CR/LF-free output contract.");
output.WriteLine(rendered);
// Do not close the caller-supplied writer here.
}
}The reporter checks only for empty strings and actual CR/LF. Each formatter's tests check its fields and format-specific meaning.
If a program receives the format as a string, some code must map that string to an implementation. That small conditional can stay.
Trace Create("json") to see the boundary where the string "json" becomes a JsonDiagnosticFormatter object. Once that object has been passed to the reporter, the reporter no longer checks the format name. This selection boundary also decides what to do with an unknown name.
public static class DiagnosticFormatterFactory
{
public static IDiagnosticFormatter Create(string format)
{
ArgumentNullException.ThrowIfNull(format);
return format switch
{
"human" => new HumanDiagnosticFormatter(),
"json" => new JsonDiagnosticFormatter(),
_ => throw new ArgumentException(
"Unsupported output format.", nameof(format))
};
}
}Assembling new DiagnosticReporter(DiagnosticFormatterFactory.Create("json")) gives the reporter a JSON formatter. A CLI can report invalid user-supplied names as argument-parsing errors rather than silently changing an unsupported format to human.
Adding a strategy changes its implementation and the factory registration while the reporter keeps its output flow. That limited scope of change connects this example to the open-closed principle. If the shared contract changes, review the reporter and existing strategies together.
If only conversion results are needed, without writing to an output device, functions can be used as follows. Render accepts a formatting function and checks its result; RenderAll applies it to a diagnostic list. The supplied function must honor the earlier side-effect-free and deterministic contract. This form serves callers that need string conversion only, unlike DiagnosticReporter, which also writes output.
For one item, start with Render(diagnostic, format). Its second parameter receives a function, and the function call inside corresponds to the main example’s Report. RenderAll repeats this operation over several diagnostics. The same position can receive an existing HumanDiagnosticFormatter object’s Format method or a conversion written directly as a function.
public static class DiagnosticFunctions
{
public static string Render(Diagnostic diagnostic, Func<Diagnostic, string> format)
{
ArgumentNullException.ThrowIfNull(diagnostic);
ArgumentNullException.ThrowIfNull(format);
var rendered = format(diagnostic);
if (string.IsNullOrEmpty(rendered) || rendered.Contains('\r') || rendered.Contains('\n'))
throw new InvalidOperationException("The formatting function violated the nonempty, CR/LF-free output contract.");
return rendered;
}
public static string[] RenderAll(
IEnumerable<Diagnostic> diagnostics,
Func<Diagnostic, string> format)
{
ArgumentNullException.ThrowIfNull(diagnostics);
ArgumentNullException.ThrowIfNull(format);
// Use Select to convert each diagnostic and ToArray to materialize the result.
return diagnostics.Select(item => Render(item, format)).ToArray();
}
}Pass a method group such as DiagnosticFunctions.RenderAll(items, new HumanDiagnosticFormatter().Format), or a lambda such as item => json.Format(item). The caller selects format, Select applies it to multiple inputs, and Render checks for empty results and CR/LF. The function remains responsible for output meaning, determinism, and avoiding side effects.
An existing formatter can supply its method as a function value. A small rule without separate settings or resource lifetime can start as a function.
First decide whether only the key changes or whether sort direction and priority change too. The lambda in OrderBy(product => product.PriceWon) selects a key. The order parameter below supplies the whole ordering rule combining OrderBy and ThenBy.
This extends the price-order example with a rule that puts a particular product first. PriorityFirst(3) creates an ordering function that prioritizes product 3; pass the returned function to Sort. Earlier, the caller passed cheapestFirst directly. Here it first supplies a preferred ID to create a function. With the main example’s IDs 3, 2, 1 and respective prices 2,000, 1,000, 1,000 won, ascending price order is 1, 2, 3, while prioritizing product 3 gives 3, 1, 2.
public sealed record CatalogProduct(int Id, decimal PriceWon);
public static class ProductOrdering
{
public static IOrderedEnumerable<CatalogProduct> CheapestFirst(
IEnumerable<CatalogProduct> products) =>
products.OrderBy(product => product.PriceWon).ThenBy(product => product.Id);
// The same rule expressed with LINQ query syntax.
public static IOrderedEnumerable<CatalogProduct> CheapestFirstQuery(
IEnumerable<CatalogProduct> products) =>
from product in products
orderby product.PriceWon, product.Id
select product;
public static IOrderedEnumerable<CatalogProduct> ExpensiveFirst(
IEnumerable<CatalogProduct> products) =>
products.OrderByDescending(product => product.PriceWon).ThenBy(product => product.Id);
public static CatalogProduct[] Sort(
IEnumerable<CatalogProduct> products,
Func<IEnumerable<CatalogProduct>, IOrderedEnumerable<CatalogProduct>> order)
{
ArgumentNullException.ThrowIfNull(products);
ArgumentNullException.ThrowIfNull(order);
// Enumerate once, then use the same input for validation and sorting.
var snapshot = products.ToArray();
foreach (var product in snapshot)
{
ArgumentNullException.ThrowIfNull(product);
if (product.Id <= 0 || product.PriceWon < 0)
throw new ArgumentOutOfRangeException(nameof(products), "IDs must be positive and prices must be nonnegative.");
}
// The strategy must only reorder elements, without adding or dropping any.
return order(snapshot).ToArray();
}
public static Func<IEnumerable<CatalogProduct>, IOrderedEnumerable<CatalogProduct>>
PriorityFirst(int productId)
{
if (productId <= 0)
throw new ArgumentOutOfRangeException(nameof(productId));
// productId is a fixed setting used by the returned function.
return products => products
.OrderBy(product => product.Id == productId ? 0 : 1)
.ThenBy(product => product.PriceWon)
.ThenBy(product => product.Id);
}
}ProductOrdering.Sort(products, ProductOrdering.CheapestFirst) and ProductOrdering.Sort(products, ProductOrdering.ExpensiveFirst) keep the same validation and result-building flow while varying the sorting rule. Passing PriorityFirst(3) puts products with ID 3 first, then orders the rest by price and ID. If none exists, the entire list is ordered by price and ID. Duplicate IDs are allowed here, so every product with the priority ID receives that priority.
CheapestFirstQuery expresses the same rule with from, orderby, and select. Here the compiler translates it to calls corresponding to .OrderBy(...).ThenBy(...), so choose the notation you find clearer.10
PriorityFirst is a higher-order function that returns a function. The returned lambda remembering productId is a closure. Instead of adding a strategy class for each setting, we create and pass a configured function; C# lambdas can capture outer variables in this way.11 Capturing a mutable configuration object lets later calls observe its changed values, so decide whether settings should be fixed or read as they change.
Enumerable.OrderBy uses deferred execution. This Sort materializes its input and result with ToArray(), completing the sort inside the call and returning an array.12
This function promises to reorder without adding or removing elements, but the Func type cannot enforce that promise. The receiver validates input; the supplied strategy should be tested for empty input, ties, and element preservation. A function that filters with Where before sorting can have the same return type while violating this contract.
Readonly<T> and readonly T[] constrain type checking; they do not freeze objects or arrays at runtime.13
TypeScript can take a product comparison function as a strategy. This example runs separately from the C# examples. Prices are nonnegative safe integers in won, and IDs are positive safe integers. Both strategies put the smaller ID first when prices tie.
This version uses the same product example and adds input validation in sortProducts. Locate the main example’s price subtraction and ID tie-breaker in the two comparisons, then trace where a negative price, a value outside the safe-integer range, or a nonpositive ID is rejected before sorting. These checks cover the range of prices and IDs; they do not check whether IDs are duplicated.
type Product = Readonly<{ id: number; priceWon: number }>;
type ProductComparison = (left: Product, right: Product) => number;
// A comparison leaves inputs unchanged and expresses order with a negative value, zero, or a positive value.
const byPriceAscending: ProductComparison = (left, right) =>
left.priceWon - right.priceWon || left.id - right.id;
const byPriceDescending: ProductComparison = (left, right) =>
right.priceWon - left.priceWon || left.id - right.id;
function sortProducts(
products: readonly Product[],
compare: ProductComparison,
): Product[] {
for (const product of products) {
if (!Number.isSafeInteger(product.priceWon) || product.priceWon < 0) {
throw new RangeError("Prices must be nonnegative safe integers.");
}
if (!Number.isSafeInteger(product.id) || product.id <= 0) {
throw new RangeError("IDs must be positive safe integers.");
}
}
// sort mutates the array, so copy the array before sorting.
// The product objects themselves are not deep-copied.
return [...products].sort(compare);
}
const products: readonly Product[] = [
{ id: 3, priceWon: 2000 },
{ id: 2, priceWon: 1000 },
{ id: 1, priceWon: 1000 },
];
const cheapFirst = sortProducts(products, byPriceAscending);
const expensiveFirst = sortProducts(products, byPriceDescending);
console.log(cheapFirst.map((product) => product.id)); // [1, 2, 3]
console.log(expensiveFirst.map((product) => product.id)); // [3, 1, 2]
console.log(products.map((product) => product.id)); // [3, 2, 1]The flow still copies the product array and calls sort, while the comparison function chooses cheaper or more expensive products first. That comparison rule is the replaceable strategy.
A callback that reports completion and one that decides sort order are both functions, but have different jobs. The comparison callback fits Strategy because it supplies one of several ways to perform the same role. Changing the order unpredictably between calls or mutating inputs breaks that promise. A function type cannot check ordering consistency, so JavaScript comparison functions must also obey conditions such as consistent results for the same input, antisymmetry, and transitivity.5
Add this code to the same file as the C# blocks in Appendices A and B to run 38 checks. It uses StringWriter to check format selection, output, and invalid input without creating files.
Read the checks for expected results on valid inputs first, then the checks that supply invalid inputs and broken implementations. Readable-text output and JSON-field checks test strategy implementations; name-to-formatter checks test selection. A writer that throws tests whether an output-device failure reaches the caller.
public static class Program
{
private static int checks;
public static void Main()
{
var diagnostic = new Diagnostic("main.pgy", 12, "E001", "Name not found.");
var multiline = new Diagnostic("main.pgy", 12, "E001", "First line\r\nSecond line \"x\"");
var human = DiagnosticFormatterFactory.Create("human");
var json = DiagnosticFormatterFactory.Create("json");
// Both versions write the same diagnostic to the same output device.
foreach (var format in new[] { "human", "json" })
{
foreach (var item in new[] { diagnostic, multiline })
{
using var before = new StringWriter(CultureInfo.InvariantCulture);
using var after = new StringWriter(CultureInfo.InvariantCulture);
new BranchingDiagnosticReporter().Report(item, format, before);
new DiagnosticReporter(DiagnosticFormatterFactory.Create(format)).Report(item, after);
Equal(before.ToString(), after.ToString());
}
}
Equal("main.pgy:12: E001: Name not found.", human.Format(diagnostic));
Equal(true, human is HumanDiagnosticFormatter);
Equal(true, json is JsonDiagnosticFormatter);
foreach (var formatter in new[] { human, json })
{
var rendered = formatter.Format(multiline);
Equal(false, string.IsNullOrEmpty(rendered));
Equal(false, rendered.Contains('\r') || rendered.Contains('\n'));
Equal(rendered, formatter.Format(multiline));
}
using (var parsed = JsonDocument.Parse(json.Format(multiline)))
{
var root = parsed.RootElement;
Equal(1, root.GetProperty("schemaVersion").GetInt32());
Equal(multiline.File, root.GetProperty("file").GetString());
Equal(multiline.Line, root.GetProperty("line").GetInt32());
Equal(multiline.Code, root.GetProperty("code").GetString());
Equal(multiline.Message, root.GetProperty("message").GetString());
}
// Check default-encoder notation separately from the parsed value.
// This notation is not required by the common contract of every JSON formatter.
var encodingProbe = new Diagnostic("main.pgy", 1, "E001", "한글<>&'\"");
using (var parsed = JsonDocument.Parse(json.Format(encodingProbe)))
{
var message = parsed.RootElement.GetProperty("message");
Equal("\"\\uD55C\\uAE00\\u003C\\u003E\\u0026\\u0027\\u0022\"", message.GetRawText());
Equal(encodingProbe.Message, message.GetString());
}
using var output = new StringWriter(CultureInfo.InvariantCulture);
var reporter = new DiagnosticReporter(human);
reporter.Report(diagnostic, output);
// Follow this writer's NewLine setting instead of hard-coding a separator.
Equal(human.Format(diagnostic) + output.NewLine, output.ToString());
output.Write("still open"); // Check that the caller-owned writer remains open.
Equal(true, output.ToString().EndsWith("still open", StringComparison.Ordinal));
Expect<ArgumentOutOfRangeException>(() => new Diagnostic("main.pgy", 0, "E001", "Error"));
Expect<ArgumentException>(() => new Diagnostic("main.pgy", 1, "E001", " "));
Expect<ArgumentException>(() => new Diagnostic("main\n.pgy", 1, "E001", "Error"));
Expect<ArgumentException>(() => DiagnosticFormatterFactory.Create("jsno"));
Expect<ArgumentNullException>(() => new DiagnosticReporter(null!));
using var rejectedOutput = new StringWriter(CultureInfo.InvariantCulture);
Expect<InvalidOperationException>(() =>
new DiagnosticReporter(new BrokenFormatter()).Report(diagnostic, rejectedOutput));
Equal("", rejectedOutput.ToString());
using var failingOutput = new FailingWriter();
Expect<IOException>(() => reporter.Report(diagnostic, failingOutput));
// Method groups and lambdas can satisfy the same function contract.
Func<Diagnostic, string> formatFunction = human.Format;
Equal(human.Format(diagnostic), DiagnosticFunctions.Render(diagnostic, formatFunction));
var jsonLines = DiagnosticFunctions.RenderAll(
new[] { diagnostic, multiline }, item => json.Format(item));
Equal(2, jsonLines.Length);
Equal(json.Format(multiline), jsonLines[1]);
var catalog = new[]
{
new CatalogProduct(3, 2000m),
new CatalogProduct(2, 1000m),
new CatalogProduct(1, 1000m)
};
var cheap = ProductOrdering.Sort(catalog, ProductOrdering.CheapestFirst);
var cheapQuery = ProductOrdering.Sort(catalog, ProductOrdering.CheapestFirstQuery);
var expensive = ProductOrdering.Sort(catalog, ProductOrdering.ExpensiveFirst);
var priority = ProductOrdering.Sort(catalog, ProductOrdering.PriorityFirst(3));
Equal("1,2,3", string.Join(",", cheap.Select(product => product.Id)));
Equal("1,2,3", string.Join(",", cheapQuery.Select(product => product.Id)));
Equal("3,1,2", string.Join(",", expensive.Select(product => product.Id)));
Equal("3,1,2", string.Join(",", priority.Select(product => product.Id)));
Equal("3,2,1", string.Join(",", catalog.Select(product => product.Id)));
Console.WriteLine($"C# checks: {checks}");
}
private static void Equal<T>(T expected, T actual)
{
if (!System.Collections.Generic.EqualityComparer<T>.Default.Equals(expected, actual))
throw new Exception($"Expected: {expected}, actual: {actual}");
checks++;
}
private static void Expect<TException>(Action action) where TException : Exception
{
try { action(); }
catch (Exception error)
{
// Unlike catch (TException), require the exact type, not a derived exception.
if (error.GetType() == typeof(TException)) { checks++; return; }
throw new InvalidOperationException(
$"Exception type mismatch: expected {typeof(TException).Name}, actual {error.GetType().Name}", error);
}
throw new InvalidOperationException($"Expected an exception of type {typeof(TException).Name}.");
}
private sealed class BrokenFormatter : IDiagnosticFormatter
{
public string Format(Diagnostic diagnostic) => "first\nsecond";
}
private sealed class FailingWriter : StringWriter
{
public override void WriteLine(string? value) =>
throw new IOException("Simulated output failure");
}
}If a formatter needs only the diagnostic, pass the diagnostic. Passing ApplicationContext, DbContext, configuration storage, and user information so the formatter can find things itself shortens the signature, but hides the information and authority it actually depends on.
An algorithm that needs part of a large component's data structure can receive a narrow query interface. Before handing over the whole object, check whether you can explain the access scope and whether testing a strategy would require starting the entire application.
This formatter's Format() is a synchronous string calculation. Accepting an implementation that calls a remote service also requires a contract for asynchronous results, cancellation, and failures.
The human-readable and JSON formatters here have no instance state, so multiple reporters can share one. A strategy that stores the latest request or a temporary buffer in fields needs review for cross-request data mixing and concurrent access. Replacing the object with a function does not resolve this if its closure retains mutable state.
A strategy that owns a file handle or network connection also needs defined creation and disposal responsibilities. State whether constructor injection transfers ownership or merely lends the resource. The writer in this example belongs to the caller, which also disposes it.
With the role names exposed, StrategyContext delegates the work and IStrategy supplies the method. Adding TInput and TResult states which strategies can be exchanged: they must accept the chosen input and produce the chosen result type.
The strategies here accept a string and return an integer. Switching from character count to word count leaves the context’s call and result type unchanged. Strategy<TInput, TResult> wraps a function, avoiding a new concrete class for every small algorithm.
using System;
var context = new StrategyContext<string, int>(new Strategy<string, int>(value => value.Length));
Console.WriteLine(context.ExecuteStrategy("generic"));
context.SetStrategy(new Strategy<string, int>(value =>
value.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length));
Console.WriteLine(context.ExecuteStrategy("one two three"));
// TYPES
interface IStrategy<TInput, TResult> { TResult ExecuteStrategy(TInput input); }
sealed class Strategy<TInput, TResult> : IStrategy<TInput, TResult>
{
private readonly Func<TInput, TResult> execute;
public Strategy(Func<TInput, TResult> execute) { this.execute = execute; }
public TResult ExecuteStrategy(TInput input) => execute(input);
}
sealed class StrategyContext<TInput, TResult>
{
private IStrategy<TInput, TResult> strategy;
public StrategyContext(IStrategy<TInput, TResult> strategy) { this.strategy = strategy; }
// Replacement strategies keep the same input and result types.
public void SetStrategy(IStrategy<TInput, TResult> strategy) { this.strategy = strategy; }
public TResult ExecuteStrategy(TInput input) => strategy.ExecuteStrategy(input);
}7
3interface Strategy<TInput, TResult> { executeStrategy(input: TInput): TResult; }
class FunctionStrategy<TInput, TResult> implements Strategy<TInput, TResult> {
constructor(private readonly execute: (input: TInput) => TResult) {}
executeStrategy(input: TInput): TResult { return this.execute(input); }
}
class StrategyContext<TInput, TResult> {
constructor(private strategy: Strategy<TInput, TResult>) {}
// Change the algorithm while retaining the context contract.
setStrategy(strategy: Strategy<TInput, TResult>): void { this.strategy = strategy; }
executeStrategy(input: TInput): TResult { return this.strategy.executeStrategy(input); }
}
const context = new StrategyContext<string, number>(new FunctionStrategy(value => value.length));
console.log(context.executeStrategy("generic"));
context.setStrategy(new FunctionStrategy(value => value.trim() === "" ? 0 : value.trim().split(/\s+/).length));
console.log(context.executeStrategy("one two three"));7
3Identical signatures can still describe different meanings. Character count and word count have different units, which the code selecting the strategy must keep straight.
The official references describe the type-parameter syntax and library contracts.14
OrderBy call. ↩enum + switch, and the State pattern's delegation to state-specific objects. ↩readonly type checking and its distinction from runtime behavior. ↩If you found the articles and experiments useful, you can buy me a coffee.
Buy me a coffee (opens in a new tab)