SOLID Principles
SOLID is five principles for arranging code so that it can change without breaking. The rings on the
Onion and Clean Architecture page rest on
them. This page takes the five one at a time: what each one means in plain words, where it came
from, and where it shows in TheYard, with the code read from the running build. The record behind
the page is ADR: Onion and SOLID, how this codebase holds them,
which also lists where a principle was deliberately not pushed further.
In plain words
Each letter of SOLID is one habit. The drawing takes them one at a time, with where TheYard shows
each one.

A preview. Open the drawing in a new page to read it full size.
- S, Single Responsibility. Each class has one job, so it has only one reason to change.
- O, Open / Closed. Add new behaviour by writing new code, and leave the code that already works
alone.
- L, Liskov Substitution. Anything that stands in for something else has to behave the same way,
so the code using it never notices the swap.
- I, Interface Segregation. Keep interfaces small and shaped to the code that calls them, so no
class has to depend on methods it never uses.
- D, Dependency Inversion. Important code depends on contracts it owns, never on the database or
the framework underneath it. The details plug into the contract, not the other way round.
Why it matters: code that follows them is easier to read and to fix, its parts lean on each other
less, and each part can be tested on its own.
What that is worth: a developer can add a second database, a new endpoint or a new page without
reopening code that already works, and the organization gets a codebase where a change lands in one
place, is covered by the tests that already exist, and does not surprise the code around it.
The words this page uses
- Principle: a rule of thumb about shape, not a law. Each one below says where TheYard stops
applying it.
- Responsibility: one reason for a piece of code to change, which usually means one group of
people who would ask for the change.
- Interface: in C#, a contract a class promises to keep: these methods, with these meanings.
- Abstraction: an interface or a base type that says what is done without saying how.
- Substitution: putting one implementation where another was, and nothing around it noticing.
- Port and adapter: the interface the inner ring declares, and the class outside that implements
it (the words are explained on the Onion and Clean Architecture page).
- Composition root: the one place, at startup, where the real classes are created and wired.
- Sealed: a C# class nothing can inherit from, so no derived type can change its meaning.
Where the five came from
Robert C. Martin collected the five in the second half of the 1990s, starting from a 1995 newsgroup
post, and published them as the principles of object-oriented design; Michael Feathers later lined
the letters up into the word SOLID. Two of the five are older than the collection: Bertrand Meyer
stated the open-closed principle in 1988, and Barbara Liskov described the substitution idea in a
1987 keynote. The other three are Martin's own.
S, single responsibility
What it means. A class, or a file, has one reason to change. Martin's later restatement is the
useful one: a reason to change is a group of people, so a module should answer to one group. When
two groups can each force a change to the same file, their changes collide.
In TheYard. A rule lives in TheYard.Domain and nowhere else. BidRules decides whether a bid
stands. StandingRules holds the one rule for raising a vehicle's shown price, and three callers
(the buyer's bids, the room's bids and the room's price to beat) all raise a price through it, so
the rule has one copy and the three cannot drift apart:
extension(Vehicle vehicle)
{
public Vehicle RaisedTo(int amount, int bidCount) =>
amount > (vehicle.CurrentBid ?? 0)
? vehicle with { CurrentBid = amount, BidCount = Math.Max(vehicle.BidCount, bidCount) }
: vehicle;
public ReserveStatus Reserve => ReserveOf(vehicle.ReservePrice, vehicle.CurrentBid);
}
Live from api/TheYard.Domain/Shared/Auction/StandingRules.cs, region raised-to, read from this build at 99df7a8.
The host keeps the same discipline at the top. Program.cs is a table of contents: each line is
one call, and the comment beside it names the file in Composition/ that holds the details, one
file per job (the stores, the sessions, the activity counters, the API's shape, the Admin tab)
(ADR: The composition root, split by job):
var builder = WebApplication.CreateBuilder(args);
var paths = HostPaths.Find(builder.Environment.ContentRootPath);
var build = new BuildInfo(builder.Configuration["APP_VERSION"] ?? "dev", builder.Configuration["APP_COMMIT"] ?? "local");
var identity = HostIdentity.From(builder.Configuration);
builder.Services.AddSingleton(paths);
builder.Services.AddSingleton(build);
builder.Services.AddSingleton(identity);
var stores = await builder.AddTheYardStoresAsync(paths, CancellationToken.None);
builder.AddTheYardObservability(stores.Backends, stores.Document, stores.SqlLog, stores.StoreLog, stores.Accessor, stores.CurrentRequest);
builder.AddTheYardSessions();
builder.AddTheYardActivity(stores.Backends, stores.Document, stores.Relational);
builder.AddTheYardApi(build);
builder.AddTheYardTelemetry(identity);
builder.AddTheYardAdmin(stores.Relational, build, identity);
builder.AddTheYardCosts(identity, stores.Relational);
builder.AddTheYardUsage();
var modules = Modules.InThisHost();
foreach (var module in modules)
{
module.Register(builder.Services, builder.Configuration);
}
builder.AddTheYardStartup(identity);
builder.AddTheYardHostedSites();
var app = builder.Build();
await app.MountTheHostedSitesAsync(app.Lifetime.ApplicationStopping);
app.UseTheYardRequestPipeline(paths, identity);
Live from api/TheYard.Api/Program.cs, region composition, read from this build at 99df7a8.
The front end holds it as a rule the build reads. Every file in src/app and src/library opens
with three lines, what it does, what it does not do and who uses it, and no file runs past three
hundred lines. A file that has to is named in the test with the reason it is allowed, which keeps
the reason where a reader of the rule will find it. The test reads the headers back, and checks
"Used by" against the files that really import it:
private static readonly string[] Folders = ["src/app", "src/library"];
private static readonly string[] Kinds = [".ts", ".tsx", ".css"];
private const string Sheets = "src";
private static readonly string[] Labels = ["Does:", "Does not:", "Used by:"];
private static readonly Dictionary<string, string> LongAllowed = new(StringComparer.Ordinal)
{
["src/components/landing/Landing/Landing.module.css"] = "the landing page's one look (hero, featured tiles, section tiles); split with Landing.tsx in the component split lane",
["src/components/layout/SideNav/SideNav.module.css"] = "the side rail's two shapes, one set of rows: one sheet shared by SideNav.tsx and the rows split out of it",
["src/components/admin/AdminPanel/AdminPanel.module.css"] = "the Admin workbench's frame: one sheet shared by AdminPanel.tsx and the parts split out of it",
["src/components/vehicle/VehicleDetail/VehicleDetail.module.css"] = "a vehicle's own page; split with VehicleDetail.tsx in the component split lane",
["src/styles/sales.css"] = "the sales pages' shared parts as one sheet, one region per part, as ADR: The sales pages set the site's look names it, so a page that takes the look reads one file",
};
Live from api/TheYard.Tests/FileHeaderTests.cs, region the-header-rule, read from this build at 99df7a8.
Where it stops. Program.cs lists twelve calls, one per area of the application, rather than twelve
classes with one method each, because a list a reader can scan is the job. The record's section
What is kept on purpose
names the others.
O, open and closed
What it means. Code should be open for extension and closed for modification: when a new case
arrives, add a class behind an interface the existing code already calls, instead of editing the
class that already works. Meyer stated it for classes in 1988; in practice it is about where a new
case lands.
In TheYard. The second database is the proof. Azure Cosmos DB arrived as new adapter classes
behind the same three ports the relational store already implemented, and the rules and the use
cases did not change
(ADR: A second store on Cosmos DB). The
composition root grew a second branch, which is where a new case is supposed to land. The relational
backend, then the document backend, as the build wires them:
var firstWait = StorePrepare.FirstWaitFrom(builder.Configuration);
var sqlStartup = new StartupTimings();
var sqlState = await sqlStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => YardDatabase.PrepareAsync(yard, seedVehicles, seedPhotos, stopping), firstWait), cancellation);
var sqlBackend = new Backend
{
Key = StoreKeys.Relational,
Name = yard.Describe(),
Database = sqlState,
Startup = sqlStartup,
Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
Bids = new BidBook(new MemoryBidStore()),
Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
Probe = _ => Task.FromResult(false),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(sqlBackend.Key, (services, _) =>
new Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserOnlyStore<YardUser, YardDbContext, string>(
services.GetRequiredService<YardDbContext>(),
services.GetService<IdentityErrorDescriber>()));
StoreAttachment SqlAttachment(DatabaseState state)
{
var sqlOptions = new DbContextOptionsBuilder<YardDbContext>();
yard.Configure(sqlOptions);
sqlOptions.AddInterceptors(new SqlLogInterceptor(sqlLog, currentRequest, TimeProvider.System));
var contexts = new ContextFactory(sqlOptions.Options);
var quietOptions = new DbContextOptionsBuilder<YardDbContext>();
yard.Configure(quietOptions);
var quietContexts = new ContextFactory(quietOptions.Options);
if (loggers.Factory is not null)
{
contexts.Attach(loggers.Factory);
}
relationalContexts.Hold(contexts, quietContexts);
return new StoreAttachment(
state,
new RelationalDiagnostics(contexts, yard.Describe(), () => loggers.Factory?.CreateLogger<RelationalDiagnostics>()),
Catalogues.Sql(contexts, yard, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Relational, servesBothSites)),
new BidBook(new EfBidStore(contexts)),
new EfActivityStore(quietContexts),
token => YardDatabase.HasSeedAsync(contexts, token));
}
if (sqlState.Ready)
{
sqlBackend.Attach(SqlAttachment(sqlState));
}
backendList.Add(sqlBackend);
Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region sql-backend, read from this build at 99df7a8.
CosmosStore? cosmos = null;
StoreSecondChance.Plan? cosmosSecondChance = null;
if (cosmosConfigured)
{
cosmos = CosmosConnection.Connect(
configuredCosmos!,
builder.Configuration["Cosmos:Database"] ?? "theyard",
builder.Configuration["Cosmos:ContainerPrefix"] ?? "",
builder.Configuration["Cosmos:Credential"] ?? "azure-cli",
AzureIds.ClientId(builder.Configuration),
storeLog);
cosmos.Recorder.CurrentRequest = currentRequest;
var cosmosStartup = new StartupTimings();
var cosmosState = await cosmosStartup.Time("prepare", stopping => StorePrepare.WithTriesAsync(() => cosmos.Starting.PrepareAsync(seedVehicles, seedPhotos, stopping), firstWait), cancellation);
var store = cosmos;
var cosmosBackend = new Backend
{
Key = StoreKeys.Document,
Name = "Azure Cosmos DB",
Database = cosmosState,
Startup = cosmosStartup,
Diagnostics = new DocumentDiagnostics(cosmos),
Inventory = new Stock(new SyntheticVehicleSource(seedVehicles, targetCount), seedPhotos),
Bids = new BidBook(new MemoryBidStore()),
Market = new Room(new Random(), builder.Configuration.GetValue("Market:GraceSeconds", Room.DefaultGraceSeconds)),
Probe = _ => Task.FromResult(false),
};
builder.Services.AddKeyedScoped<IUserStore<YardUser>>(cosmosBackend.Key, (_, _) => new CosmosUserStore(store, TimeProvider.System));
StoreAttachment CosmosAttachment(DatabaseState state) => new(
state,
new DocumentDiagnostics(store),
Catalogues.Cosmos(store, targetCount, Catalogues.UpkeepFor(keepCatalogues, defaultStore, StoreKeys.Document, servesBothSites)),
new BidBook(new CosmosBidStore(store)),
new CosmosActivityStore(store),
store.Starting.ProbeAsync);
if (cosmosState.Ready)
{
cosmosBackend.Attach(CosmosAttachment(cosmosState));
}
backendList.Add(cosmosBackend);
cosmosSecondChance = new StoreSecondChance.Plan(
cosmosBackend,
() => store.Starting.PrepareAsync(seedVehicles, seedPhotos, CancellationToken.None),
async state =>
{
var attachment = CosmosAttachment(state);
await attachment.Inventory.WarmAsync(CancellationToken.None);
await attachment.Bids.LoadAsync(CancellationToken.None);
cosmosBackend.Attach(attachment);
});
}
Live from api/TheYard.Api/Shared/Wiring/StoreRegistration.cs, region cosmos-backend, read from this build at 99df7a8.
The same shape holds the documents you are reading. A new page is one row in the server's
catalogue and one entry in the front end's list of pages, and a test fails if the two ever
disagree. This page arrived that way: two rows, no change to the code that serves documents.
Where it stops. The ports themselves changed once for the second store: every member became a
Task, because the document store has no synchronous driver. That one change touched every caller
once, and the record says so plainly rather than pretending the door was never opened
(ADR: The ports learn to wait).
L, Liskov substitution
What it means. If code works with a type, it must keep working with anything that stands in for
that type, without checking which one it got. Liskov's 1987 keynote put it as a property of types:
a subtype must behave the way the supertype's users expect. For interfaces, that means any
implementation can replace any other and the callers cannot tell.
In TheYard. The gate is the proof. The same xUnit suite runs on both stores: once with the
relational store underneath, and again with Cosmos DB, by pointing the process at the account and
running dotnet test again. Not a second suite written for the second store: the same facts, the
other adapter, the same answers. The if in the block below is why the second pass is not run on
every version: it runs when the version touched the API, the Cosmos infrastructure or the three
specs that read both stores, and is carried forward from the version that last ran it otherwise.
Between the two passes sit the twelve tests that do need the live account, which are the one set
written for the second store. From the gate's own workflow, the job that reads the Cosmos DB account (the
SQLite pass runs beside it in a job of its own since 1.0.5.4):
- name: The Cosmos DB passes
if: always()
run: |
d="$RAW/dotnet.result"; n="$RAW/node.result"; : > "$d"; : > "$n"
t() { local s=$SECONDS code=0; "$@" || code=$?; echo "$code $((SECONDS - s))"; }
export Cosmos__AccountEndpoint="$COSMOS_ENDPOINT" Cosmos__Credential=emulator
read code s < <(t env Cosmos__CatalogueAccountEndpoint="$COSMOS_ACCOUNT" bash -c 'dotnet test api --no-build --filter "Store=cosmos" --logger "trx;LogFileName=xunit-live.trx" --results-directory "$RAW/trx" > "$RAW/xunit-live.txt" 2>&1')
echo "live=$code" >> "$d"; echo "live_s=$s" >> "$d"
export Cosmos__ContainerPrefix="tests-"
if [ "$COSMOS_NEEDED" = 1 ]; then
read code s < <(t bash -c 'dotnet test api --no-build --filter "Store!=cosmos" --logger "trx;LogFileName=xunit-cosmos.trx" --results-directory "$RAW/trx" > "$RAW/xunit-cosmos.txt" 2>&1')
echo "oncosmos=$code" >> "$d"; echo "oncosmos_s=$s" >> "$d"
else echo "oncosmos=skipped" >> "$d"; echo "oncosmos_s=0" >> "$d"; fi
export YARD_API_PREBUILT=1 YARD_WEB_PREVIEW=1
export PLAYWRIGHT_JSON_OUTPUT_FILE="$RAW/browser-cosmos.json" PLAYWRIGHT_JSON_OUTPUT_NAME="$RAW/browser-cosmos.json"
if [ "$COSMOS_NEEDED" = 1 ]; then
read code s < <(t bash -c 'npx playwright test tests/e2e/store-toggle.spec.ts tests/e2e/account.spec.ts tests/e2e/admin.spec.ts --workers=2 --retries=1 --reporter=list,json > "$RAW/browser-cosmos.txt" 2>&1')
echo "browser_cosmos=$code" >> "$n"; echo "browser_cosmos_s=$s" >> "$n"
else echo "browser_cosmos=skipped" >> "$n"; echo "browser_cosmos_s=0" >> "$n"; fi
for port in 5173 5210; do fuser -k "$port/tcp" 2>/dev/null || true; done
cat "$d" "$n"
Live from .github/workflows/gate.yml, region both-stores, read from this build at 99df7a8.
MemoryBidStore is the smaller case. It implements IBidStore in a dictionary, with the same
compare-and-set rule the two real stores keep, and the tests of the use cases hand it in where a
real store would go, so a use case can be tested with no database and no mocking framework. It stands in for a real store in production too: a backend whose store has
not come up yet bids against it, and the bids are forgotten at restart. That is a deliberate limit,
written down in ADR: The relational store.
Where it stops. Substitution is not complete everywhere, and the record says where: the Cosmos
DB user store does not move the email claim when an address changes, and nothing in the site changes
an address today (Known gaps in substitution).
Sealing classes helps hold the principle from the other side: a class nothing can inherit from is a
class no derived type can change the meaning of, which is why TheYard seals by default
(Sealed by default).
I, interface segregation
What it means. No class should be forced to depend on methods it does not use. Shape an interface
to the code that calls it, and prefer several small interfaces to one wide one.
In TheYard. The auction has three ports, not one repository, because the catalogue, the photos
and the bids are read by different code at different times:
public interface IVehicleSource
{
Task<IReadOnlyList<Vehicle>> LoadAsync(CancellationToken cancellation);
}
public interface IPhotoManifestSource
{
Task<IReadOnlyList<PhotoEntry>> LoadAsync(CancellationToken cancellation);
}
public interface IBidStore
{
Task<IReadOnlyList<StoredBid>> LoadAsync(CancellationToken cancellation);
Task<IReadOnlyList<StoredStanding>> LoadStandingsAsync(CancellationToken cancellation);
Task<StoredStanding?> ReadStandingAsync(string vehicleId, CancellationToken cancellation);
Task<IReadOnlyList<StoredBid>> BidsOnAsync(string vehicleId, CancellationToken cancellation);
Task<bool> TrySaveAsync(string userId, string vehicleId, BidState state, VehicleStanding standing, string? expectedVersion, CancellationToken cancellation);
Task ClearAsync(string userId, CancellationToken cancellation);
}
public interface IVehicleCatalogue
{
int Target { get; }
CatalogueFillPace Pace { get; }
Task<int> FilledAsync(CancellationToken cancellation);
Task FillAsync(IReadOnlyList<CatalogueEntry> batch, CancellationToken cancellation);
Task<SegmentCounts> CountAsync(CatalogueFilter filter, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> PageAsync(CatalogueFilter filter, CatalogueOrder order, int skip, int take, CancellationToken cancellation);
Task<IReadOnlyList<CatalogueEntry>> FindAsync(IReadOnlyCollection<string> ids, CancellationToken cancellation);
Task<InventoryFacets> FacetsAsync(CancellationToken cancellation);
}
Live from api/TheYard.Application/Shared/Auction/Ports.cs, region ports, read from this build at 99df7a8.
IStoreExperiment, the port behind the Admin tab's performance proof, has one method, because the
Admin tab asks one question.
Where it stops. IActivityStore and ILogStore each carry one writer beside the handful of
reads their callers ask for, and are not split, because splitting them would double the interfaces
and allow no new swap. They stay whole
until a caller needs only half
(What is kept on purpose).
D, dependency inversion
What it means. The important code should not depend on the details underneath it; both should
depend on an abstraction, and the abstraction should belong to the important code. In the rings,
that is the move that makes the whole shape possible: the inner ring declares the interface it
needs, the outer ring implements it, and at compile time every arrow points inward.

A preview. Open the port and its adapters in a new page to zoom in and follow it.
In TheYard. TheYard.Application declares IBidStore. EfBidStore in the relational adapter and
CosmosBidStore in the document adapter implement it. Composition/StoreRegistration.cs decides
which one a store gets, and every class receives what it needs through its constructor. Four tests
read the compiled host and fail the build if a handler reaches a database, a Cosmos DB client or the
service container, composes the bid services itself, queries a database, or registers a service
anywhere but the composition root:
[Fact]
public void Endpoints_never_reach_a_store_or_the_service_container()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.That().MeetCustomRule(IsPartOfAnEndpointClass)
.ShouldNot().HaveDependencyOnAny(
"Microsoft.EntityFrameworkCore",
"Microsoft.Azure.Cosmos",
"Microsoft.Data.SqlClient",
"Microsoft.Data.Sqlite",
"System.Data.Common",
"TheYard.Infrastructure.Cosmos",
"TheYard.Infrastructure.YardDbContext",
"TheYard.Infrastructure.Shared.Stores.ContextFactory",
"System.IServiceProvider",
"Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Endpoints_reach_the_auction_only_through_the_Application_ring()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.That().MeetCustomRule(IsPartOfAnEndpointClass)
.ShouldNot().HaveDependencyOnAny(
"TheYard.Application.Shared.Auction.BidBook",
"TheYard.Application.Shared.Auction.Room",
"TheYard.Application.Shared.Auction.Stock")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Endpoints_see_the_auction_and_the_request_s_store_never_a_backend()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.That().MeetCustomRule(type => IsPartOfAnEndpointClass(type)
&& !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Admin")
&& !InNamespace(Outermost(type).Namespace, "TheYard.Api.Features.Health"))
.ShouldNot().HaveDependencyOnAny("TheYard.Api.Shared.Stores.Backend", "TheYard.Api.Shared.Stores.Backends", "TheYard.Infrastructure.Cosmos.Shared.Stores.CosmosStore")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void The_host_uses_the_sheds_assembly_only_from_the_shed_s_own_site()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.That().MeetCustomRule(type => Outermost(type).Name is not ("ShedSite" or "ShedApplication"))
.ShouldNot().HaveDependencyOnAny(["TestProject"])
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void The_host_never_queries_a_database_itself()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.ShouldNot().HaveDependencyOnAny(
"Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions",
"Microsoft.EntityFrameworkCore.RelationalQueryableExtensions",
"Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions",
"Microsoft.EntityFrameworkCore.DbSet",
"Microsoft.Data.SqlClient",
"Microsoft.Data.Sqlite",
"System.Data.Common.DbCommand",
"System.Data.Common.DbConnection",
"Microsoft.Azure.Cosmos.QueryDefinition",
"Microsoft.Azure.Cosmos.Container")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void Services_are_registered_only_in_the_composition_root()
{
var result = Types.InAssembly(typeof(Program).Assembly)
.That().MeetCustomRule(type => !IsCompositionRoot(type))
.ShouldNot().HaveDependencyOnAny(
"Microsoft.Extensions.DependencyInjection.IServiceCollection",
"Microsoft.Extensions.DependencyInjection.ServiceCollectionServiceExtensions",
"Microsoft.Extensions.DependencyInjection.Extensions.ServiceCollectionDescriptorExtensions")
.GetResult();
Assert.True(result.IsSuccessful, Explain(result));
}
[Fact]
public void The_host_finds_nothing_at_runtime_outside_its_composition_root()
{
Assert.Empty(RuntimeLookups(typeof(Program).Assembly.Location));
}
[Fact]
public void A_route_or_a_handler_is_handed_its_settings_never_the_configuration()
{
using var module = ModuleDefinition.ReadModule(typeof(Program).Assembly.Location);
var taking = module.GetTypes()
.Where(type => !IsCompositionRoot(type) && (IsPartOfAnEndpointClass(type) || Outermost(type).Name.EndsWith("Handler", StringComparison.Ordinal)))
.SelectMany(type => type.Methods)
.Where(method => method.Parameters.Any(parameter => parameter.ParameterType.FullName == "Microsoft.Extensions.Configuration.IConfiguration"))
.Select(method => $"{method.DeclaringType.FullName}.{method.Name} takes IConfiguration")
.ToList();
Assert.True(taking.Count == 0, string.Join(Environment.NewLine, taking));
}
[Fact]
public void The_application_ring_finds_nothing_at_runtime_at_all()
{
Assert.Empty(RuntimeLookups(typeof(TheYard.Application.Shared.Auction.StandingReader).Assembly.Location));
}
[Fact]
public void Claude_is_asked_only_through_the_one_client_that_reports_its_usage()
{
string root = Repo.Root();
string adapter = Path.Combine("api", "TheYard.Api", "Shared", "Usage", "AnthropicClaudeClient.cs");
var sources = new[] { "TheYard.Data", "TheYard.Domain", "TheYard.Application", "TheYard.Infrastructure", "TheYard.Infrastructure.Cosmos", "TheYard.Api" }
.SelectMany(project => Directory.EnumerateFiles(Path.Combine(root, "api", project), "*.cs", SearchOption.AllDirectories))
.Concat(Directory.EnumerateFiles(Path.Combine(root, "src"), "*.ts*", SearchOption.AllDirectories))
.Where(path => !path.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal)
&& !path.Contains($"{Path.DirectorySeparatorChar}bin{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
.ToList();
Assert.Contains(sources, path => path.EndsWith(adapter, StringComparison.Ordinal));
var calling = sources
.Where(path => !path.EndsWith(adapter, StringComparison.Ordinal))
.Where(path => File.ReadAllText(path) is var text
&& (text.Contains("api.anthropic.com", StringComparison.OrdinalIgnoreCase) || text.Contains("using Anthropic", StringComparison.Ordinal) || text.Contains("@anthropic-ai/", StringComparison.Ordinal)))
.Select(path => Path.GetRelativePath(root, path))
.ToList();
Assert.True(calling.Count == 0, "these files reach the Anthropic API around IClaudeClient: " + string.Join(", ", calling));
Assert.Contains(typeof(TheYard.Application.Shared.History.IUsageLog), typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient).GetConstructors().Single().GetParameters().Select(p => p.ParameterType));
Assert.True(typeof(TheYard.Application.Shared.Claude.IClaudeClient).IsAssignableFrom(typeof(TheYard.Api.Shared.Usage.AnthropicClaudeClient)));
}
[Fact]
public void The_host_opens_no_socket()
{
var wrong = TheYard.Rules.SocketRule.Opens(typeof(Program).Assembly, name => name == "Program" || name.EndsWith("Module", StringComparison.Ordinal));
Assert.True(wrong.Count == 0, string.Join(Environment.NewLine, wrong));
}
Live from api/TheYard.Tests/OnionTests.cs, region host, read from this build at 99df7a8.
Where it stops. The server's clock is a static, read once at the edge and handed inward as a
value, rather than a TimeProvider injected into every handler: the rules take the clock as an
argument, which is what lets their tests fix time, and the extra parameter would buy the tests
nothing (ADR: Onion and SOLID).
Five principles, one table
How the build holds them
- Architecture tests
- 19
- File header tests
- 4
- Sealed-by-default tests
- 5
- Files with the header
- 164 of 164
Numbers read from the build when the page is opened. The architecture tests, by name:
Data_depends_on_nothing_outside_the_BCL
Data_has_no_behaviour
Domain_depends_on_nothing_outside_the_BCL_and_Data
Application_depends_only_on_Domain_Data_and_the_BCL
Domain_never_reaches_the_disk_the_network_or_the_clock
Application_never_reaches_the_disk_or_the_network
The_document_store_adapter_borrows_only_the_shared_user_from_the_relational_one
Infrastructure_adapts_and_decides_nothing
Endpoints_never_reach_a_store_or_the_service_container
Endpoints_reach_the_auction_only_through_the_Application_ring
Endpoints_see_the_auction_and_the_request_s_store_never_a_backend
The_host_uses_the_sheds_assembly_only_from_the_shed_s_own_site
The_host_never_queries_a_database_itself
Services_are_registered_only_in_the_composition_root
The_host_finds_nothing_at_runtime_outside_its_composition_root
A_route_or_a_handler_is_handed_its_settings_never_the_configuration
The_application_ring_finds_nothing_at_runtime_at_all
Claude_is_asked_only_through_the_one_client_that_reports_its_usage
The_host_opens_no_socket
References
- Robert C. Martin, The Principles of OOD:
the five principles in one line each, from the author who collected them, with the 1995 origin.
- Robert C. Martin, The Single Responsibility Principle
(2014): the restatement this page uses, a reason to change is a group of people.
- Bertrand Meyer, Object-Oriented Software Construction
(1988; second edition 1997, online): the book that stated the open-closed principle.
- Barbara Liskov, Data Abstraction and Hierarchy
(keynote 1987, published 1988): the origin of the substitution principle.
- Architectural principles, .NET architecture guides:
Microsoft's version of the same ground, with dependency inversion and single responsibility as
principles for a .NET application.