📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What does "clean code" actually mean in practice? How do readability and maintainability differ, and how would you tell whether a piece of C# code is clean?

Defines clean code in practical terms, separates readability (understanding code now) from maintainability (changing it safely later), and gives observable tests for clean C#.

Beginner Theory Beginner clean-code code-quality csharp maintainability readability

🎯 Key points

  • Clean code = code another developer can read, understand and change safely with little effort
  • Readability: how fast a reader understands what the code does right now
  • Maintainability: how cheaply and safely the code can be changed later (tests, coupling, cohesion)
  • High cohesion = a class or method has one well-defined purpose; low cohesion = it mixes unrelated jobs
  • Explicit dependencies via constructor injection (built-in DI, TimeProvider) instead of statics and new-ing up services
  • Automated tests pin behaviour so changes are safe; SOLID principles underpin the structure
  • Consistency enforced by .editorconfig, analysers and dotnet format rather than taste arguments
  • Clean is contextual: a throwaway script and a payments service need different bars

⏱ 30-second answer

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:

  • Readability: how quickly someone understands what the code does today: clear names, small focused methods, obvious control flow, a consistent style enforced by .editorconfig and analysers.
  • Maintainability: how cheaply and safely it can be changed later: automated tests that pin behaviour, high cohesion (each class has one purpose), low coupling, and explicit dependencies injected through the constructor with ASP.NET Core's built-in DI instead of statics.

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 CalculateOrderTotal instead of Process, 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 for IOrderRepository and TimeProvider in its constructor and the DI container supplies them, instead of calling DateTime.Now or 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 .editorconfig plus 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 var while 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 vs maintainability

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

Observable signs of clean C#

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

Principles underneath

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

When the bar changes

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

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate sees clean code as something practical that changes cost, not a dogma, and can separate understanding from changing.

Green flags

  • Distinguishes readability from maintainability with an example
  • Mentions explicit dependencies, tests and coupling, not only naming
  • Mentions automated style enforcement (editorconfig, analysers)
  • Admits the bar depends on context

Red flags

  • Only talks about formatting or comment density
  • Quotes rules dogmatically ("methods must be under 5 lines")
  • Thinks clean code means rewriting everything

📚 Learn in depth

1. Why code quality is an economic question

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.

2. Readability: how humans read code

Readers keep a small number of things in working memory at once. Code is readable when it fits that limit:

  • Names carry meaning, so the reader doesn't keep a mental mapping (x means "the order total excluding GST").
  • One level of abstraction per method: a method that mixes OrderPlaced business steps with StringBuilder manipulation forces context switches.
  • Linear flow: guard clauses and early returns instead of four levels of nesting.

3. Maintainability: how code resists change

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.

4. What .NET gives you for free

  • Nullable reference types (<Nullable>enable</Nullable>) make null-ness part of the signature.
  • Analysers (CA and IDE rules, built into the SDK) and .editorconfig encode team style so it is enforced, not debated.
  • dotnet format fixes style automatically in CI.
  • Records, primary constructors and pattern matching remove boilerplate that hides intent.

5. Measuring it (roughly)

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.

Try it yourself

  1. Take a method you wrote six months ago. Time how long it takes you to explain it aloud. Rename three things and re-time.
  2. Enable <AnalysisLevel>latest-recommended</AnalysisLevel> in a project and read the top five warnings by count.
  3. Run dotnet format --verify-no-changes on a repo and see how much style drift exists.
  4. Pick a class with the most commits in git log --format= --name-only | sort | uniq -c | sort -rn | head and list why it changes so often.

💻 Code

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";
}

⚠ Common mistakes

  • Mistake: Treating clean code as formatting and naming only. Why it is wrong: the expensive problems are coupling and hidden dependencies, not brace style. Instead: automate style with .editorconfig and dotnet format, and spend review time on structure.
  • Mistake: Assuming readable means maintainable. Why it is wrong: nicely named code that calls 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.
  • Mistake: Applying the same polish to every piece of code. Why it is wrong: it wastes time on throwaway scripts and slows delivery. Instead: match the bar to the code's lifetime and risk.
  • Mistake: Rewriting working code because it "isn't clean". Why it is wrong: rewrites without tests introduce regressions and deliver no user value. Instead: clean up incrementally as you touch code (the boy scout rule).
  • Mistake: Arguing personal taste in reviews. Why it is wrong: it burns goodwill and is inconsistent. Instead: agree conventions once, encode them in analysers, and move on.
  • Mistake: Using comments to explain confusing code. Why it is wrong: comments drift out of date. Instead: rename and extract so the code explains itself; keep comments for why.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions classes having one responsibility Why: Checks they can recognise and fix low cohesion in real C# code
    How to answer

    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.

  2. When: Candidate mentions consistent style or editorconfig Why: Checks they know how style rules are enforced across IDEs and the build
    How to answer

    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.

  3. When: Candidate mentions good names Why: Checks they can turn 'good names' into concrete rules
    How to answer

    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.

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me