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

📚 Interview question

People say methods and classes should be small. How small is small? When should you split a method or class, and when does splitting actually make the code harder to follow?

Explains the real criteria for splitting methods and classes (one level of abstraction, one reason to change, cohesion), and the failure mode of over-splitting into tiny, scattered indirection.

Intermediate Theory Intermediate clean-code code-quality cohesion csharp refactoring small-methods

🎯 Key points

  • Size is a symptom; the real tests are one level of abstraction and one reason to change
  • Split a method when it mixes levels (business steps plus string/SQL plumbing) or needs comments to mark sections
  • Split a class when its fields fall into groups used by different methods (low cohesion, LCOM); aim for functional cohesion
  • Extracted methods must have names that hide detail; if the name restates the code, don't extract
  • Over-splitting: many 2-line methods force the reader to jump around and lose the story
  • Splitting a class must not break encapsulation: don't make private state public just so the new class can reach it
  • Rough heuristics: method fits on a screen (~20-30 lines), cyclomatic complexity under ~10 (CA1502 default is 25), more than 3-4 parameters suggests a parameter object
  • Extract with IDE refactorings, and run the unit tests after every extraction to prove behaviour didn't change

⏱ 30-second answer

Small is not a line count. A method is the right size when it works at one level of abstraction: it reads like a list of steps, each step named, with the details pushed into well-named helpers. A class is the right size when it has one reason to change and its fields are used together (high cohesion).

Split when a method mixes business steps with plumbing, when you feel the need for section comments, or when a class's fields fall into groups used by different methods. Don't split when the extracted piece has no better name than the code itself, or when the reader would have to jump through five two-line methods to follow one simple flow. The trade-off is locality versus abstraction: every split hides detail but adds a jump.

🗣 Full answer (senior)

How I would answer this in an interview

"I don't think of it as a line count. My test for a method is whether it works at one level of abstraction. A good PlaceOrderAsync reads like the business process: validate, reserve stock, take payment, save, publish an event. If in the middle of that I'm suddenly building a SQL string or formatting an email body, the method is mixing levels and that part should be extracted behind a name. Another strong signal is section comments like // calculate discounts: that comment wants to be a method name.

For classes I look at cohesion: do all the methods use most of the fields? If half the methods use the repository and the email client and the other half use the PDF renderer, that's two classes sharing a file. And I look at reasons to change: if pricing changes and template changes both edit the same class, it should probably be split.

The mistake I see on the other side is over-splitting. Someone reads 'methods should be four lines' and you end up with ValidateOrder calling ValidateLines calling ValidateLine calling CheckQuantity, each in a different file, and to understand a ten-line rule you open six tabs. If the extracted method's name just repeats its body, it isn't hiding anything. My rule is that a split has to make the caller easier to read without making the callee harder to find."


When to split

Signal What to do
Method mixes business steps and low-level detail Extract the detail behind an intention-revealing name
Section comments inside a method Each section becomes a method named after the comment
Deep nesting (3+ levels) Guard clauses, then extract the inner block
Class fields used by disjoint sets of methods Extract class along the field groups
Two unrelated reasons to change Split by responsibility
Hard to unit test one behaviour in isolation Extract it so it can be tested

When not to split

Signal Why splitting hurts
Extracted name restates the code (AddOneToCount) No information hidden, just an extra jump
Logic is a simple linear sequence that reads fine The story is easier to follow in one place
Pieces always change together Splitting creates shotgun surgery
Only one caller and the method is already short Indirection without benefit

Rough heuristics (not rules)

Measure Rough guide
Method length Fits on one screen (~20-30 lines)
Cyclomatic complexity Aim under ~10; CA1502 warns at 25 by default
Parameters More than 3-4 suggests a parameter object
Class coupling CA1506 flags very high coupling (defaults 95 for types)

Production example

A 220-line InvoiceService.Generate method mixed tax rules, PDF layout and email sending. Splitting it into InvoiceCalculator, InvoicePdfRenderer and InvoiceMailer let the team unit test GST rules for the first time (14 tests), and a later PDF template change no longer needed a review from the finance-rules owner.

🔍 What the interviewer is checking

Checks the candidate has judgment about decomposition rather than a memorised rule, and knows over-splitting is a real failure mode.

Green flags

  • Uses levels of abstraction and cohesion as the criteria
  • Gives a concrete signal (section comments, field clusters)
  • Names over-splitting and its cost
  • Mentions doing it with IDE refactorings under tests

Red flags

  • Quotes a fixed line limit as law
  • Thinks more classes always means better design
  • Never considered readability of the caller vs callee

📚 Learn in depth

1. Why size correlates with difficulty

Human working memory holds a handful of items. A long method forces the reader to keep many variables and branches in mind at once. But the real cost driver is how many concepts the method juggles, not how many lines it has. A 40-line switch mapping enum values to strings is easy; a 15-line method with three nested loops and mutations is not.

2. Levels of abstraction

  PlaceOrderAsync          <- business level: steps
    ├─ ValidateOrder       <- rule level
    ├─ ReserveStockAsync   <- integration level
    │    └─ HttpClient...  <- transport level
    └─ SaveAsync           <- persistence level
         └─ SQL            <- storage level

A method should sit on one row. When it reaches down two rows, extract.

3. Cohesion, measured

Lack of Cohesion of Methods (LCOM) counts how many method pairs share no fields. High LCOM means the class is really several classes. You can eyeball it: draw which methods touch which fields; disconnected clusters are candidate classes.

  Fields:   _repo  _mailer  _pdf  _taxRules
  Calc()     x                       x
  Save()     x
  Render()                   x
  Email()           x        x
  => clusters {Calc, Save}, {Render, Email}

4. The cost of indirection

Every extraction adds a jump. Jumps are cheap when the name tells you enough that you don't need to follow it (CalculateGst). They are expensive when you must follow them to understand anything (DoStep2). The JIT doesn't care: small methods are often inlined, so performance is rarely a reason to keep code long.

5. Locality of behaviour

Code that changes together should live together. Splitting a concept across files by technical layer (one file for validation, one for mapping, one for rules) can make a simple change touch many files. Prefer splits along business concepts over splits by technical role.

Try it yourself

  1. Enable CA1502 with dotnet_diagnostic.CA1502.severity = warning and lower the threshold via a CodeMetricsConfig.txt file containing CA1502: 10; see what lights up.
  2. Take a 100-line method and use Extract Method only where you can write a name better than the code. Count how many extractions survive.
  3. Draw the method/field matrix for your largest service class and look for clusters.
  4. Over-split a method on purpose into 2-line pieces, then ask a colleague to explain it; time both versions.

💻 Code

An order placement method before and after extracting at one level of abstraction.

// Before: business steps mixed with plumbing.
public async Task

⚠ Common mistakes

  • Mistake: Treating a line limit as a rule ("no method over 10 lines"). Why it is wrong: it produces fragmented code and ignores that complexity, not length, is the problem. Instead: check levels of abstraction and reasons to change.
  • Mistake: Extracting methods whose names restate the body (IncrementCounter). Why it is wrong: the reader gains nothing and pays a jump. Instead: only extract when the name hides meaningful detail.
  • Mistake: Splitting classes by technical role (OrderValidator, OrderMapper, OrderHelper) for one simple feature. Why it is wrong: one business change now touches many files. Instead: split along business concepts and keep things that change together together.
  • Mistake: Breaking encapsulation when extracting a class, e.g. turning private fields into public properties so the new class can read them. Why it is wrong: invariants that one class protected can now be broken from anywhere. Instead: move the data with the behaviour that uses it, or pass only the values needed as parameters.
  • Mistake: Keeping a 'god' service because "it's all order stuff". Why it is wrong: low cohesion makes every change risky and tests need every dependency mocked. Instead: split along field clusters and responsibilities.
  • Mistake: Extracting without tests, or not re-running them after each step. Why it is wrong: manual extraction can change behaviour (captured variables, evaluation order, exception timing). Instead: use IDE refactorings and run the test suite after every extraction.
  • Mistake: Believing small methods hurt performance. Why it is wrong: the JIT inlines small methods, and the cost is negligible next to I/O. Instead: optimise structure for readers; measure with BenchmarkDotNet if in doubt.

🏛 Senior insight: trade-offs

The senior framing is cost of a jump versus cost of a context switch. Extraction removes context switches (mixed levels) but adds jumps. A good extraction's name is trustworthy enough that the reader doesn't follow it. When you see people Ctrl+clicking through every helper to understand a flow, the code has been split past the point of usefulness.

It helps to know the classic types of cohesion (Constantine and Yourdon), from worst to best, because they tell you why a class feels wrong:

Cohesion type What groups the code Example Verdict
Coincidental Nothing Utils with string, date and HTTP helpers Split
Logical Same category of thing ExportService doing CSV, PDF and Excel via a flag Usually split by type
Temporal Runs at the same time StartupTasks doing cache warm-up, migrations, emails Split by purpose
Sequential / communicational Output of one step feeds the next, or same data InvoiceCalculator steps on one invoice Fine
Functional Everything serves one well-defined task GstCalculator Ideal

What the framework gives you: IDE Extract Method/Class/Interface refactorings, CA1502 (complexity) and CA1506 (coupling) analysers, and Visual Studio's Code Metrics window. Use metrics to find hotspots, then use judgment.

Option When it fits Cost When not to
Extract method Mixed abstraction levels, section comments Small, IDE-assisted Name no better than the body
Extract class Field clusters, two reasons to change New type, DI registration Pieces always change together
Inline method Over-split, pointless indirection Small The method is reused or tested independently
Leave it long Flat, linear, readable (e.g. a mapping) None It has branches and mutations

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions cohesion or field clusters 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 over-splitting or too many classes Why: Checks they can spot and reverse over-engineering
    How to answer

    Over-engineering is complexity that today's requirements do not justify. I detect it through symptoms with numbers behind them: a one-field change touching many files, interfaces with one implementation, configuration options nobody sets, patterns like CQRS or event sourcing without the problems they solve, and microservices that always deploy together. I reverse it incrementally rather than with a rewrite: inline single-use abstractions, merge layers that only pass data through, consolidate services that share a release cycle, and delete unused options, each step behind tests. I also address why it happened, because otherwise it grows back.

🛠 Real-world problems: how you handle them

A 220-line invoice method nobody wants to touch
Situation
An invoicing service at [company] with a single `Generate` method of [~220] lines mixing GST rules, PDF layout and email sending. It produces [N thousand] invoices a month and finance-sensitive changes queue behind one developer.
Signals
PRs touching the file take [3-4] days to review; two rounding bugs in [6] months; developers avoid the file; SonarQube cognitive complexity of [60+] on the method.
Investigation
Read the method with a highlighter for levels of abstraction; drew a method/field matrix; used `git log -L` on the method to see which parts changed together; checked existing coverage with coverlet (near zero for the method).
Resolution
Immediately: added characterisation tests around `Generate` using a set of [20] real-shaped synthetic invoices and Verify snapshots. Then: IDE Extract Method into named steps, followed by Extract Class into `InvoiceCalculator`, `InvoicePdfRenderer` and `InvoiceMailer`, one PR per step.
Prevention
CA1502 at a lowered threshold as a warning on new code, Sonar quality gate on new-code cognitive complexity, and a review checklist item: 'does each method sit on one level of abstraction?'

How to tell it (STAR)

**S:** Our invoicing service had one [220]-line method that mixed tax rules, PDF layout and email, and every change to it was slow and risky. **T:** I was asked to [add a new invoice type] and decided to make the method safe to change first. **A:** I wrote characterisation tests with snapshots, then extracted step by step with the IDE refactorings, one small PR each, ending with three focused classes. I kept validation together rather than splitting it into tiny pieces because those rules always change together. **R:** The new invoice type took [2] days instead of the estimated [5], GST rules got [14] unit tests, and we had [no] invoicing defects in the following [quarter].

↩ Usually asked after

More in Clean Code

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me