Software Architecture
SOLID principles with an online shop: what each one means and what guards it
The SOLID principles are five pieces of advice for writing code you can change without fear. Each letter is the initial of one principle. This post explains them one at a time with an online shop that charges orders, works out shipping, sends emails and stores invoices. For each principle you get what it is, why it was born, what happens to the shop when it's broken, the code before and after, and who tells you when someone breaks it: the compiler, a test, or nobody. All the sample code, with its tests, can be downloaded from the solid-principles-online-shop repository at NippysoftLabs.
| Letter | Principle | In one sentence |
|---|---|---|
| S | Single Responsibility | Each piece has one reason to change. |
| O | Open/Closed | You add something new without rewriting what already works. |
| L | Liskov Substitution | If you swap a piece for another that claims to do the same, everything keeps working. |
| I | Interface Segregation | Each client gets what's theirs, and nothing more. |
| D | Dependency Inversion | Business rules don't depend on a specific provider. |
Each principle has its own origin. Open/closed was stated by Bertrand Meyer in 1988, and substitution comes from Barbara Liskov's work. The other three were put forward by Robert C. Martin, who named single responsibility in the late 1990s, from earlier ideas, though he suspects he may have taken the name from Bertrand Meyer. Martin also brought all five together: he started in 1995, on a programmers' forum, and kept extending them in articles and books. He meant them for classes, the pieces an object-oriented program is built from. In 2000 he published Design Principles and Design Patterns, which starts from a problem anyone who maintains a program knows: over the years, every change costs more and breaks things far from where you touched. That article has four of the five, but not single responsibility. The SOLID acronym, which puts the five initials into one easy word, came later. Martin told InfoQ in 2018 that around 2004 Michael Feathers wrote to him that, reordered, the principles spelled SOLID: "I think it was 2004 and Michael wrote me an e-mail, and said that if you rearranged the principles they spell SOLID."
In The Principles of OOD (object-oriented design), Martin tells the story: "In March of 1995, in comp.object, I wrote an article that was the first glimmer of a set of principles for OOD that I have written about many times since." And about their scope: "The first five principles are principles of class design." The 2000 article names the symptom they're meant to prevent: "The software starts to rot."
S, single responsibility: the email can't break the payment
What it is and what it's for
A piece of code should have one reason to change. A reason to change is a source of change requests: payment rules change for different reasons than the wording of an email. Behind each reason there's usually an actor, the person or team asking for those changes. It keeps what one actor asks for from breaking what another relies on.
Why it was born
Martin explains it with people, not code. When two teams touch the same class, a change one of them asks for ends up breaking the other, and nothing scares people more than a program failing over something unrelated to what they asked for.
In the shop
One class charges the card, saves the order and sends the confirmation email. Marketing wants to greet customers by first name, and whoever codes it cuts the name at the first space. A customer named Ana, with no surname, pays. She's charged, the order is saved and, while building the email, the program fails and the website shows her an error. Ana thinks she didn't buy anything, but she's already been charged. Marketing asked for a greeting, and what broke was the sale.
The code
Before, one method does all three steps. The marketing line looks for the first space with IndexOf; there's none in Ana, IndexOf returns -1 and the slice fails with an error, ArgumentOutOfRangeException:
public sealed class OrderProcessor(IPaymentGateway payments, IOrderStore orders)
{
public List<string> SentEmails { get; } = [];
public CheckoutResult Place(Order order, string cardToken)
{
var payment = payments.Charge(order.Id, cardToken, order.Total);
switch (payment.Status)
{
case PaymentStatus.Approved:
break;
case PaymentStatus.Declined:
return CheckoutResult.Declined;
default:
// Unknown (or a status this code does not know): we do not know whether it was paid, so the
// order is not saved as paid and no confirmation goes out.
return CheckoutResult.PaymentUnknown;
}
orders.Save(order);
// Marketing's change: greet by first name, cut at the first space. For "Ana" IndexOf
// returns -1 and the slice throws, after the card was charged and the order saved.
var firstName = order.CustomerName[..order.CustomerName.IndexOf(' ')];
SentEmails.Add($"Hi {firstName}, your order {order.Id} is confirmed.");
return CheckoutResult.Placed;
}
}
The test puts it in plain sight: the call throws, and still there's one charge of 2500 cents, one saved order and no email sent. The payment handling is right on purpose: only an approved payment saves the order and sends the email; a declined one, or one with no answer from the provider, does neither. Another test checks all three states. So the failure you see is the mixed responsibilities, not a payment bug.
The fix separates the two reasons to change. Sales keeps Checkout, which charges and saves, with not a single line of email. On top of that, the example puts each part in its own project, a part of the code that compiles separately. Two classes would satisfy the principle; separate projects are an organizing choice that leaves the boundary to the compiler:
public sealed class Checkout(IPaymentGateway payments, IOrderStore orders)
{
public CheckoutResult Place(Order order, string cardToken)
{
// The order id is the idempotency key: with a gateway that keeps the contract, a retry of the
// same order returns the first charge instead of charging again.
var payment = payments.Charge(order.Id, cardToken, order.Total);
switch (payment.Status)
{
case PaymentStatus.Approved:
orders.Save(order);
return CheckoutResult.Placed;
case PaymentStatus.Declined:
return CheckoutResult.Declined;
default:
// Unknown, or a status this code does not know: never report it as declined.
return CheckoutResult.PaymentUnknown;
}
}
}
The email moves to Orders.Notifications, marketing's project, and receives an order that has already been charged and saved: it builds the text and nothing else. A name with no space is used whole, so Ana and Ana Ruiz get the same greeting, Hi Ana:
public static class ConfirmationEmail
{
public static string Render(Order order) =>
$"Hi {FirstName(order.CustomerName)}, your order {order.Id} is confirmed.";
// Marketing's rule: greet by the first word of the name. A name with no space ("Ana") is kept whole.
internal static string FirstName(string fullName)
{
var name = fullName.Trim();
var space = name.IndexOf(' ');
return space < 0 ? name : name[..space];
}
}
What guards it: the compiler
The sales project, Orders.Domain, doesn't reference marketing's: it can't use anything in it. If someone calls the email from checkout again, the program doesn't compile:
SendFromCheckout.cs(1,14): error CS0234: The type or namespace name 'Notifications' does not exist in the namespace 'Orders' (are you missing an assembly reference?)
Adding that reference doesn't work either. Marketing already uses sales, and if sales used marketing, each would need the other to compile: the build stops with error MSB4006. On top of that, a test checks the assemblies, the compiled output of each project, and confirms that marketing depends on sales and never the other way round. A modular monolith with compiler-enforced boundaries uses the same boundary; here it separates two teams.
What it doesn't guard: the email is plain text and copies the name as is, so <b>Ana</b> Ruiz gives Hi <b>Ana</b>, tags included. If the email were HTML, those characters would have to be encoded so they aren't read as markup. An empty name gives Hi , your order o-1 is confirmed. and a null one throws NullReferenceException. Those are marketing rules, with their own owner.
Separating the code doesn't guarantee the email arrives either. Nothing in the repo sends it: ConfirmationEmail only builds the text. In a real system, if the process stops between saving the order and sending the email, the notification is lost. The usual fix is a transactional outbox (Transactional Outbox): save the order and a message to send the confirmation in the same database transaction, and let another process send the messages from that table.
Martin's definition, in The Single Responsibility Principle: "each software module should have one and only one reason to change". And the note that makes it useful: "This principle is about people."
O, open/closed: the store pickup that charged for shipping
What it is and what it's for
You can add something new without modifying code that already works. It keeps every new feature from forcing you to touch, test and redeploy the old ones.
Why it was born
Bertrand Meyer stated it in 1988 and Martin adopted it. If adding something means editing what's there, every new feature puts what already worked at risk. His ideal is a plugin system, where new things plug in without touching old ones.
In the shop
The shop has standard shipping, at 4.99 € and free from 50 €, and express shipping, at 9.99 €. One day it adds store pickup on the website, but nobody touches the code that works out shipping. That code is a list of cases ending in one that charges anything it doesn't recognize as standard. Whoever comes to pick up an order pays 4.99 € for shipping, and nobody notices until the complaints arrive.
The code
Before, each option is an arm of a switch, and the last one charges 4.99 for any option it doesn't know:
public static class ShippingCost
{
public static decimal For(string option, decimal orderTotal) => option switch
{
"standard" => orderTotal >= 50m ? 0m : 4.99m,
"express" => 9.99m,
// The fallback. "store-pickup" was added to the website, not here, and lands in this arm.
_ => 4.99m,
};
}
After, there are two ways to extend, and it pays not to mix them. The first is a new option that uses a rule that already exists: one line in a configuration file, with no code change. Store pickup is the third line and uses the free rule:
[
{ "name": "standard", "kind": "free-over", "price": 4.99, "threshold": 50 },
{ "name": "express", "kind": "flat", "price": 9.99 },
{ "name": "store-pickup", "kind": "free" }
]
The second is a new behavior, such as half price or a price by weight: a new piece that fulfils IShippingRule, the price rule, and is added at startup. Each kind of price, such as flat, free or free over a threshold, is one of those pieces. Neither the catalog, the part that picks the rule for each option, nor its user, OrderTotals, which adds shipping to the cart total, changes. The test shows it with a half-price rule written in the test project, outside the assembly that holds the catalog and OrderTotals, which are used exactly as compiled:
public void After_a_new_rule_from_another_assembly_works_without_changing_the_catalog_or_its_consumer()
{
var catalog = new ShippingCatalog([.. Rules, new HalfPriceRule()], [new ShippingOption("weekend", "half-price", Price: 9.99m)]);
// 9.99 / 2 = 4.995, rounded to cents like every other price: 5.00.
Assert.Equal(5.00m, catalog.Quote("weekend", 30m));
Assert.Equal(35.00m, new OrderTotals(catalog).Total(30m, "weekend"));
Assert.NotEqual(typeof(ShippingCatalog).Assembly, typeof(HalfPriceRule).Assembly);
Assert.Equal(typeof(ShippingCatalog).Assembly, typeof(OrderTotals).Assembly);
}
Half of 9.99, rounded to the cent, is 5.00, and a 30 € cart with that option adds up to 35.00. If the weekend option, the one using half price, is configured but the rule isn't registered, the application doesn't start: option 'weekend': no rule for kind 'half-price'.
An option that doesn't exist, such as drone, throws an error instead of charging another option's price. That's the fix for the earlier failure: the default case silently put a price on something it didn't know. An unknown option has no right price, so the only safe answer is an error the website can show and the logs can record.
What guards it: tests on the configuration
The compiler doesn't help here: a switch with a default case compiles just the same, and nobody compiles the configuration file. So the file is read with strict options: a misspelled key, such as "prize" instead of "price", a price in quotes, a null name or a repeated key makes the load fail. Each option is also validated at startup, and every error is reported together. Five badly written options give these seven errors at once:
"option 'drone': no rule for kind 'by-weight'",
"option 'express': flat needs a price of 0 or more with at most 2 decimals",
"option 'Express': name used twice (names compare ignoring case)",
"option 'Express': free takes no price and no threshold",
"option 'standard': free-over needs a price of 0 or more with at most 2 decimals",
"option 'standard': free-over needs a threshold greater than 0",
"an option has an empty name",
One test loads the same config/shipping.json that's checked into the repository, so a mistake in the file fails in continuous integration (CI), the tests that run on every change, and not in production.
What it doesn't guard: option names are compared exactly, so Store-Pickup with capitals is an unknown option. And the shipping calculation accepts a total with more than 2 decimals, such as 49.995.
Martin sums it up as "You should be able to extend the behavior of a system without having to modify that system." And on plugins: "Plugin systems are the ultimate consummation, the apotheosis, of the Open-Closed Principle."
L, Liskov substitution: the payment provider that charges 19 € instead of 19.99 €
What it is and what it's for
If a piece promises to do the same as another, whoever uses it shouldn't notice the swap. It lets you change provider, database or service without breaking whoever uses them.
Why it was born
Barbara Liskov raised it in her work on types and data abstraction, and in 1994 she formalized it with Jeannette Wing in A Behavioral Notion of Subtyping. Martin added it to his principles. The idea is that what you can guarantee about a type stays true for any other that claims to be of that type.
In the shop
The shop charges through one payment provider and adds another that works in cents. Whoever writes the adapter, the piece that translates what the shop asks into what the provider understands, tests it with 20 € and everything works. In production, a 19.99 € product is charged as 19 €. A declined card makes the website show an error instead of a declined-card message. And if the provider charges but its answer never arrives, the website shows an error, the customer pays again and is charged twice. The cart code is the same as always; what fails is that the new piece doesn't keep its promise.
Two answers look alike and aren't. A decline is the provider saying no: nothing was charged, and the customer can try another card. An unknown result is no answer at all, from a timeout or a dropped connection, and the card may have been charged. Treating it as a decline is the expensive mistake: the customer is told nothing was charged when it may have been. If they leave, they're charged with no order; if they place a new order, they pay twice. The right move is to retry the same order with the same key, which returns the charge if it happened, or to ask the provider.
The code
The promise is written on the IPaymentGateway interface, the contract every payment provider keeps. The amount is in euros, greater than 0, at most 999,999.99 and with at most 2 decimals. A declined card returns Declined and doesn't throw. With no answer from the provider, it returns Unknown, never Declined. The idempotency key, which is the order id, makes a retry return the first charge instead of charging again, also after an Unknown. And a decline doesn't use up that key: the customer can pay the same order with another card. Checkout turns this into three results: Placed, Declined or PaymentUnknown, which doesn't save the order yet and doesn't treat it as declined.
The naive adapter compiles against that interface and passes the test with 20 €:
public sealed class NaiveCentsGateway(CentsPaymentApi api) : IPaymentGateway
{
public PaymentResult Charge(string idempotencyKey, string cardToken, decimal amount)
{
// The cast applies to amount before the multiplication: 19.99 becomes 19, then 1900 cents.
// The key is not passed on, and a declined card throws CardDeclinedException out of here.
var charge = api.CreateCharge((long)amount * 100, cardToken);
return new PaymentResult(PaymentStatus.Approved, charge.Id, charge.AmountCents / 100m);
}
}
(long)amount * 100 converts before multiplying: 19.99 becomes 19 and then 1900 cents. It also doesn't pass the key on, and it lets CardDeclinedException and TimeoutException escape. With the same sales Checkout, an order of 19.99 is charged as 1900 cents, a declined card crashes the sale and, if the answer gets lost, both attempts throw TimeoutException and there are 2 charges. Against the contract suite, the 15 checks every adapter must pass, it breaks 12:
"approved card is charged the exact amount: wrong result",
"amount under one euro: threw ArgumentOutOfRangeException: amount must be at least 1 cent (Parameter 'amountCents')",
"largest allowed amount: wrong result",
"declined card returns Declined: threw CardDeclinedException: card declined by the issuer",
"after a decline the same key can be charged with another card: threw CardDeclinedException: card declined by the issuer",
"no answer from the provider returns Unknown, not Declined: threw TimeoutException: the provider did not answer in time",
"after an Unknown result, a retry with the same key returns the charge that happened: threw TimeoutException: the provider did not answer in time",
"same key charges once: wrong result",
"three decimals throws ArgumentException: wrong result",
"amount over the limit throws ArgumentException: wrong result",
"empty key throws ArgumentException: wrong result",
"empty card token throws ArgumentException: wrong result",
The fixed adapter checks the input with the same rules as the others, multiplies before converting, turns the decline into Declined and the missing answer into Unknown, and passes the key on:
public sealed class CentsGateway(CentsPaymentApi api) : IPaymentGateway
{
public PaymentResult Charge(string idempotencyKey, string cardToken, decimal amount)
{
PaymentInput.Check(idempotencyKey, cardToken, amount);
try
{
// amount has at most 2 decimals and is at most 999999.99, so amount * 100 is a whole number that fits a long.
var charge = api.CreateCharge(decimal.ToInt64(amount * 100), cardToken, idempotencyKey);
return new PaymentResult(PaymentStatus.Approved, charge.Id, charge.AmountCents / 100m);
}
catch (CardDeclinedException)
{
return new PaymentResult(PaymentStatus.Declined, "", 0m);
}
catch (Exception ex) when (ex is TimeoutException or IOException)
{
// No answer is not a "no": the card may have been charged. A retry with the same key finds out.
return new PaymentResult(PaymentStatus.Unknown, "", 0m);
}
}
}
It keeps all 15 checks. With the answer lost, the first attempt gives PaymentUnknown, with one charge and no saved order; the retry gives Placed and there's still a single charge of 1999 cents. A declined order can be paid later with another card.
What guards it: one contract suite
The compiler sees nothing: all three adapters implement IPaymentGateway and compile the same. What sees the behavior is PaymentGatewayContract.Verify, which runs the same 15 checks on each one: the reference one, an in-memory simulated provider that defines how to behave, the naive one and the fixed one.
Reach of the suite: it checks each adapter against the repo's simulated provider. It shows the adapter keeps the contract if the provider behaves like the simulated one, not that a real provider does; for that, the same suite has to run against the provider's test environment.
What it doesn't guard: a key or a card made only of spaces is accepted. Reusing a key with another amount returns the first charge with no error. It only works in euros. And only TimeoutException and IOException count as no answer; the code library a real provider ships, its SDK, has its own exceptions.
Martin turns it into usage rules in the 2000 article: "derived methods should expect no more and provide no less." And in Solid Relevance he says it without talking about classes: "A program that uses an interface must not be confused by an implementation of that interface."
I, interface segregation: the tracking page that could refund money
What it is and what it's for
Nobody should depend on operations they don't use. If an interface, the list of operations one piece offers the others, serves several clients, it gets split into small interfaces, one per client. It gives each client only the operations it can use, and keeps other clients' changes from dragging it along.
Why it was born
Martin raised it for classes with many clients: instead of one huge interface for everyone, one per client. If a client depends on something it doesn't use, it still has to be recompiled and redeployed when that something changes.
In the shop
The shop has a single interface for everything done with orders: checking the status, preparing shipments, marking an order as shipped, refunding money and exporting to accounting. The page where customers check where their order is reads the status and nothing else. Even so, it gets the whole interface. To test it you have to write a double, a fake version for tests, with all five operations, four of them only there to throw a not-implemented error. The page gets an object that can refund money, so a bug in it could do just that. And when finance asks for partial refunds, the page's double stops compiling over a change that has nothing to do with it.
The code
Before, a single interface, IOrderOperations, with the five operations. The tracking page gets all of it:
public partial interface IOrderOperations
{
OrderStatus GetStatus(string orderId); // tracking page
IReadOnlyList<string> OrdersToPick(); // warehouse
void MarkShipped(string orderId); // warehouse
void Refund(string orderId, decimal amount); // finance
string ExportForAccounting(); // finance
}
After, three interfaces, one per client: IOrderStatusReader for the page, IPickingQueue for the warehouse and IRefunds for finance:
public partial interface IOrderStatusReader
{
OrderStatus GetStatus(string orderId);
}
/// <summary>What the warehouse calls.</summary>
public partial interface IPickingQueue
{
IReadOnlyList<string> OrdersToPick();
void MarkShipped(string orderId);
}
/// <summary>What finance calls.</summary>
public partial interface IRefunds
{
void Refund(string orderId, decimal amount);
string ExportForAccounting();
}
A single class, OrderBook, implements all three. Segregation changes what each client sees, not the class behind it: the same OrderBook ships one order, refunds another, and the page sees both statuses. The page's double now has a single method. The partial keyword on the interfaces isn't part of the principle: it's only there so the sample that doesn't compile can add an operation without editing this file.
What guards it: a test and the compiler
A test pins the exact list of operations each client depends on. If someone hands the page a bigger interface again, it fails:
public void After_each_consumer_depends_only_on_the_operations_it_calls()
{
Assert.Equal(["GetStatus"], OperationsOf(typeof(Examples.Isp.After.TrackingPage)));
Assert.Equal(["MarkShipped", "OrdersToPick"], OperationsOf(typeof(PickingScreen)));
Assert.Equal(["ExportForAccounting", "Refund"], OperationsOf(typeof(RefundDesk)));
Assert.False(typeof(IRefunds).IsAssignableFrom(typeof(IOrderStatusReader)));
}
The compiler shows what skipping it costs. A sample adds PartialRefund to the big interface and to the finance one, and two things fail: the page's double from before and OrderBook, which is the class that really does refunds. The page's double from after compiles unchanged:
OrderOperations.cs(9,109): error CS0535: 'OrderBook' does not implement interface member 'IRefunds.PartialRefund(string, decimal)'
OrderOperations.cs(9,37): error CS0535: 'OrderBook' does not implement interface member 'IOrderOperations.PartialRefund(string, decimal)'
TrackingPageDoubles.cs(4,41): error CS0535: 'FatTrackingDouble' does not implement interface member 'IOrderOperations.PartialRefund(string, decimal)'
What it doesn't guard: segregation limits what each client is given, not what it can reach. Code that treats the page's IOrderStatusReader as the OrderBook behind it, with a type cast, can still refund.
A side note, about API design more than this principle: the shop had a single product in its API for the public website and the warehouse, and the website got the cost price, the supplier and the aisle. Anyone who opened the browser's developer tools saw how much the shop makes on each lamp. The repo fixes it with one response per client, StorefrontProduct and WarehouseProduct, and a test that compares the fields of the website's response with an exact list: sku, name and price.
In the 2000 article: "Many client specific interfaces are better than one general purpose interface". And in 2020, the cost of skipping it: "Clients do depend on methods they don’t call, if they have to be recompiled and redeployed when one of those methods is modified."
D, dependency inversion: invoices tied to one cloud
What it is and what it's for
Business rules don't depend on a specific provider. It's the other way round: the business states what it needs, in its own words, such as storing an order's invoice, and the infrastructure implements it. Creating an interface or passing it through the constructor isn't enough: what matters is who defines it and in what terms. It lets you change provider without touching the business, and test the business without the real provider.
Why it was born
In top-down designs, the important pieces, the rules, depend on the detail pieces: the database, the network or a provider. Martin saw that this is fragile, because a change in a detail drags the rules along, and he put it forward as the mechanism that makes open/closed possible.
In the shop
The shop stores each invoice in a provider's cloud. The invoice code creates that cloud's client itself and writes the bucket name right there. If the shop switches provider tomorrow, the invoice code has to be rewritten, and every invoice test writes to the real cloud. A common first fix is to take the interface the provider itself ships and pass it through the constructor. You can now test with a double, but the business still talks about buckets and object paths, and a provider shaped differently forces a change all the same.
The code
Before, the invoice class creates the cloud client itself and fixes the bucket, the cloud folder the invoices go to:
public sealed class InvoiceService
{
private readonly CloudBucketClient _bucket = new("invoices-prod");
public string Archive(string orderId, string customer, decimal amount)
{
var path = $"invoices/{orderId}.txt";
var document = $"{orderId};{customer};{amount.ToString(CultureInfo.InvariantCulture)}";
_bucket.UploadObject(path, Encoding.UTF8.GetBytes(document));
return $"{_bucket.Bucket}/{path}";
}
}
The class takes nothing when it's created: there's no way to pass it another provider or a test one. The interface-only version takes ICloudBucket, but that interface belongs to the provider's SDK and its operations are the provider's, UploadObject and Bucket. The real fix puts the IInvoiceArchive port in the business, declared in its terms: store an order's document. The CloudInvoiceArchive adapter, in another project, implements it and is the only one that knows the SDK. In the tests, the business runs with an in-memory archive.
What guards it: a dependency test, helped by the compiler
A dependency test sets the rule: it reads the references of the domain's compiled assembly and accepts only .NET ones (System.*). With the SDK reference added and used, it fails:
== Orders.Domain.csproj + ProjectReference FakeCloud.Storage + ArchiveDirectly.cs
[0]: Item: "FakeCloud.Storage"
Error: Orders.Domain references FakeCloud.Storage
The compiler helps, but it doesn't set the rule. Orders.Domain references no other project, so a sample that uses the cloud from the domain doesn't compile:
ArchiveDirectly.cs(1,7): error CS0246: The type or namespace name 'FakeCloud' could not be found (are you missing a using directive or an assembly reference?)
But nothing stops you from adding the reference. And if it's added and not used, the compiler drops it and the test passes: with no use there's no coupling to report. That's why the test draws the boundary, not what the compiler does with references.
What it doesn't guard: the adapter accepts an empty order id, which gives invoices/.txt, and one of 300 characters, which makes a 327-character path.
Martin's two lines in the 2000 article: "Depend upon Abstractions. Do not depend upon concretions." And: "If the OCP states the goal of OO architecture, the DIP states the primary mechanism."
From code to system
The same five pieces of advice work when the pieces are services talking over the network. With the shop:
- S. Another service, the notifications one, sends the email from saved orders. If that service fails, the sale still went through; so that the email isn't lost, the order reaches it through a transactional outbox.
- O. A new shipping option is a configuration line, validated at startup.
- L. Every payment provider runs the same contract suite before it reaches production.
- I. Each client, the tracking page, the warehouse or finance, sees only the operations it uses.
- D. The business defines the port and each cloud is an adapter.
Between services one more rule shows up: version the data contract. If the order service renames amount to total, the service that reads the message doesn't find amount, leaves it at 0 and carries on with no error. That's why each contract carries a version number. A change old readers can live with, such as adding an optional field, bumps the minor version, from 1.1 to 1.2. One that breaks them requires a new major version, 2.0. The repo stores the schema of each released version and compares every version with the previous one. Calling that rename 1.2 doesn't pass:
public void Renaming_amount_cannot_ship_as_a_minor_version()
{
var breaking = SchemaCompatibility.BreakingChanges(
Frozen("1.1"), SchemaCompatibility.SchemaOf(typeof(Examples.Contracts.After.Proposals.OrderPlaced)));
Assert.Equal(["$.amount: required property removed"], breaking);
Assert.Equal("1 breaking change(s) need version 2.0, not 1.2", SchemaCompatibility.CheckVersionBump("1.1", "1.2", breaking));
Assert.Null(SchemaCompatibility.CheckVersionBump("1.1", "2.0", breaking));
}
The comparison also flags a property that loses its list of allowed values (enum) and becomes free text: an old reader that only accepts those values rejects any other one with JsonException. The test reports it as $.status: enum removed; values are no longer limited to "New", "Paid" and requires version 2.0. Removing one value from the list isn't flagged, because the old reader still reads every value that remains.
Before you release a contract between services, it's worth deciding who signs off a major version and which consumers must be told: the test says the change breaks, not who to tell.
The whole repo runs in one process. Between real services, the same checks belong in each side's CI, and the repo doesn't cover that. Splitting into services doesn't fix mixed owners on its own either, as Martin warns in 2020: "You can create a tangled microservice, or a tangled set of microservices if you mix code that changes for different reasons."
What guards each principle
| Principle | In the shop | Who tells you |
|---|---|---|
| Single responsibility | Marketing's email can't break the payment | The compiler, the build and an architecture test |
| Open/closed | Store pickup is a configuration line | Tests that load and validate config/shipping.json |
| Liskov substitution | Every payment adapter keeps the same contract | A suite of 15 checks |
| Interface segregation | The tracking page can only read the status | A test of operations per client, and the compiler |
| Dependency inversion | Invoices don't depend on one cloud | A dependency test, helped by the compiler |
| Data contract | A renamed field can't ship as a minor version | Stored schemas and a version rule |
Run with the .NET 10.0.401 SDK (runtime 10.0.12) on Windows 11, with no database, network or cloud: the payment provider and the cloud are in-memory stand-ins.
Conclusion
SOLID doesn't ask for pretty classes. It asks that what changes for one reason doesn't break what changes for another, that new things get in without touching old ones, that a piece keeps its promise, that each client gets what's theirs and that the business doesn't depend on a provider. The useful part is knowing, for each one, who tells you when someone breaks it.
dotnet test and pick the principle that costs you most today: copy its test into your solution before you touch the code.References
- The Principles of OOD, Robert C. Martin (butunclebob.com, HTTP only)
- Design Principles and Design Patterns, Robert C. Martin, 2000 (eli.sdsu.edu, PDF)
- The Single Responsibility Principle (blog.cleancoder.com)
- The Open Closed Principle (blog.cleancoder.com)
- A Behavioral Notion of Subtyping, Liskov and Wing, 1994 (cs.columbia.edu, PDF)
- Solid Relevance (blog.cleancoder.com)
- Pattern: Transactional outbox, Chris Richardson (microservices.io)
- Uncle Bob Martin on Clean Software, Craftsperson, Origins of SOLID, DDD, & Software Ethics, InfoQ, 2018 (infoq.com)
Tags
Share this post
Subscribe
Get the latest posts delivered right to your inbox.
Leave a comment