Defines clean code in practical terms, separates readability (understanding code now) from maintainability (changing it safely later), and gives observable tests for clean C#.
Clean code is code that another developer can read, understand and change safely without needing the author in the room. Two qualities sit underneath it:
.editorconfig and analysers.They overlap but are not the same: a beautifully named method that calls DateTime.Now, a static cache and the database directly is readable but painful to change. The trade-off is that cleanliness costs time up front, so match the bar to how long the code will live and how risky it is to change.
"For me clean code means code that the next person can read, understand and change safely without having to ask me. I usually split that into two things. Readability is about understanding: can I read a method top to bottom and know what it does, because the names say what they mean, the method does one thing and nothing surprising happens. Maintainability is about change: when the business changes the discount rules, can I make that change in one place, run the tests and be confident I didn't break invoicing.
In .NET that shows up very concretely. Names like
CalculateOrderTotalinstead ofProcess, methods that fit on a screen, classes with high cohesion and one reason to change, which is the single responsibility principle from SOLID applied day to day. Dependencies are explicit: a class asks forIOrderRepositoryandTimeProviderin its constructor and the DI container supplies them, instead of callingDateTime.Nowor a static singleton buried in business logic, so I can unit test it with a fake clock. Nullable reference types are on so the signature tells you what can be null, and.editorconfigplus the analysers enforce style, so code reviews talk about design rather than braces.The mistake I see is treating clean code as a style checklist: people argue about
varwhile the real problem is a class that talks to five services and can't be tested. I'd rather have slightly ugly formatting and good boundaries than the other way round. Clean code is the cheapest code to change next month."
| Readability | Maintainability | |
|---|---|---|
| Question it answers | Can I understand this now? | Can I change this safely later? |
| Main levers | Names, small methods, clear flow, formatting | Tests, low coupling, high cohesion, explicit dependencies (DI) |
| Measured by | Time for a newcomer to explain the code | Lead time and defect rate for changes in that area |
| Typical failure | Cryptic names, 300-line methods | Hidden dependencies, static state, no tests |
| Sign | What it looks like |
|---|---|
| Intention-revealing names | IsEligibleForFreeShipping(order) instead of Check(o) |
| Small, cohesive units | Methods doing one thing at one level of abstraction; classes with one purpose |
| No surprises | A Get... method never writes to the database |
| Explicit dependencies | Constructor-injected TimeProvider, IOrderRepository, registered in Program.cs |
| Honest signatures | Nullable annotations, CancellationToken on async methods |
| Tests as documentation | Total_includes_gst_for_australian_customers |
| Consistent style | Enforced by .editorconfig + dotnet format in CI |
| Principle | How it shows up as clean code |
|---|---|
| Single responsibility (SRP) | Small, cohesive classes with one reason to change |
| Dependency inversion (DIP) | Business code depends on interfaces; DI wires implementations |
| Open/closed | New discount types added as new classes, not new if branches |
| KISS / YAGNI | No abstractions until a second real use appears |
| Code | Reasonable bar |
|---|---|
| One-off data fix script | Readable, reviewed, not polished |
| Internal tool | Readable, a few tests around the risky parts |
| Core order / payment domain | Full: tests, clear boundaries, analysers as errors |
In an order service, the GST calculation lived in three controllers with slightly different rounding. Moving it into one well-named, constructor-injected GstCalculator with eight unit tests took half a day; the next rate-related change took 20 minutes instead of two days of hunting, and the rounding defects (about 1 in 2,000 invoices off by a cent) stopped.
Checks that the candidate sees clean code as something practical that changes cost, not a dogma, and can separate understanding from changing.
Green flags
Red flags
Code is written once and read many times: during reviews, debugging, onboarding and every later change. Studies of developer time consistently show reading and understanding dominate writing. So every minute saved for a reader pays back many times.
Cost of a change = time to understand + time to change + time to verify + risk of breaking something
^ readability ^ design ^ tests ^ coupling
Clean code attacks each term.
Readers keep a small number of things in working memory at once. Code is readable when it fits that limit:
x means "the order total excluding GST").OrderPlaced business steps with StringBuilder manipulation forces context switches.Maintainability comes from structure more than style:
Change request
|
v
How many places must change? <- duplication, shotgun surgery
|
Can I see everything it touches? <- hidden dependencies, statics
|
Can I prove it still works? <- tests, seams
The ISO/IEC 25010 quality model splits maintainability into modularity, reusability, analysability, modifiability and testability, which is a useful vocabulary in design reviews.
<Nullable>enable</Nullable>) make null-ness part of the signature..editorconfig encode team style so it is enforced, not debated.dotnet format fixes style automatically in CI.No metric captures clean code fully, but some correlate: cyclomatic complexity per method (CA1502), class coupling (CA1506), churn hotspots (files changed most often), and lead time for changes in an area. Use them as prompts for a conversation, never as targets.
<AnalysisLevel>latest-recommended</AnalysisLevel> in a project and read the top five warnings by count.dotnet format --verify-no-changes on a repo and see how much style drift exists.git log --format= --name-only | sort | uniq -c | sort -rn | head and list why it changes so often.An order total calculation, before and after. Same behaviour; the second is easier to read and to change.
// Before: works, but the reader has to decode everything.
public class OrderSvc
{
public decimal Calc(Order o)
{
decimal t = 0;
foreach (var l in o.Lines) t += l.Qty * l.Price;
if (o.Cust.Country == "AU") t = t * 1.1m; // magic number: GST
if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday && t > 100) t -= 10; // hidden time dependency
return Math.Round(t, 2);
}
}
// After: names explain intent; time is injected so the rule is testable.
namespace Shop.Orders;
public sealed class OrderTotalCalculator(TimeProvider clock)
{
private const decimal GstRate = 0.10m;
private const decimal TuesdayDiscount = 10m;
private const decimal TuesdayDiscountThreshold = 100m;
public decimal CalculateTotal(Order order)
{
var subtotal = order.Lines.Sum(line => line.Quantity * line.UnitPrice);
var withGst = order.Customer.IsAustralian ? subtotal * (1 + GstRate) : subtotal;
return Math.Round(withGst - TuesdayDiscountFor(withGst), 2, MidpointRounding.AwayFromZero);
}
private decimal TuesdayDiscountFor(decimal amount) =>
clock.GetLocalNow().DayOfWeek == DayOfWeek.Tuesday && amount > TuesdayDiscountThreshold
? TuesdayDiscount
: 0m;
}
public sealed record Order(Customer Customer, IReadOnlyList<OrderLine> Lines);
public sealed record OrderLine(int Quantity, decimal UnitPrice);
public sealed record Customer(string CountryCode)
{
public bool IsAustralian => CountryCode == "AU";
}
.editorconfig and dotnet format, and spend review time on structure.DateTime.Now, statics and the database directly is still hard to change and test. Instead: also check dependencies are explicit and behaviour is covered by tests.Juniors describe clean code as a list of rules; seniors describe it as lowering the cost of the next change. That reframing settles most debates: a rule is worth following when it makes change cheaper or safer in this codebase. It also explains why consistency beats any single style choice: a team that follows one convention reads code faster than one with five good ones.
The framework already gives you most of the mechanical part: analysers, nullable reference types, .editorconfig and dotnet format. Seniors push the mechanical part into tooling so that human review is about boundaries, naming of domain concepts and test quality.
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
| Automated style (editorconfig, dotnet format) | Always, from day one | Low, one-off setup | Never skip it |
| Incremental clean-up while touching code | Mature codebases | Small, spread over time | Code about to be deleted |
| Dedicated refactoring work | Hotspots with high churn and defects | Days to weeks | Stable code nobody changes |
| Rewrite | Rarely: tech is dead and behaviour is well specified | Very high, risky | Almost always |
Cohesion is how strongly the parts of a module belong together. A highly cohesive class has methods that work on the same data towards one purpose, so a change to that concept happens in one place. Low cohesion shows up as Utils or Manager classes with unrelated methods, fields that only one or two methods use, and classes that change for many different reasons. I improve it by grouping code around domain concepts and features, moving methods to the data they use, and splitting classes whose fields form separate clusters.
I commit an .editorconfig at the repo root with root = true. It holds formatting (indentation, new lines), .NET code style preferences such as file-scoped namespaces, and severities for analyser and code style rules via dotnet_diagnostic.<id>.severity. Visual Studio, VS Code and Rider all read it, so style no longer depends on the editor. To enforce it, I set EnforceCodeStyleInBuild so IDE rules run during dotnet build, and run dotnet format --verify-no-changes in CI.
A good name is intention-revealing: it tells the reader what something is and why it exists without making them read the implementation. overdueInvoices beats list2; IsEligibleForRefund() beats Check().
In C# follow the .NET conventions: PascalCase for types, methods and properties, camelCase for locals and parameters, _camelCase for private fields, I prefix on interfaces, Async suffix on Task-returning methods, and booleans phrased as questions (IsActive, HasLines). Avoid abbreviations (cust, amt) and type names in identifiers (customerList, strName): the compiler already knows the type and the name goes stale when the type changes. Use the business's words. The trade-off is length: names should grow with scope, so i is fine in a three-line loop but not as a field.
Last updated 23 Nov 2026.