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

📚 Interview question

What are the god class and long method smells? Why do they keep appearing, especially in .NET services and handlers, how do you recognise them, and how would you break one up safely?

Covers the god class and long method smells: their causes in .NET (fat services, handlers and controllers), how to recognise them with metrics and reading, and how to break them up with extract method, extract class and splitting by responsibility.

Intermediate Theory Intermediate code-quality code-smells csharp god-class long-method refactoring

🎯 Key points

  • Long method: does several things at different levels of abstraction; hard to name, test and change
  • God class: one class owns too many responsibilities; no magic line count, but a few hundred lines or 7+ constructor dependencies is a common review trigger, and 1,000+ is almost always a god class
  • They grow by accretion: adding 'one more if' is always cheapest in the moment
  • Recognise by reasons to change, constructor dependency count, CA1502/CA1506 and cognitive complexity, change frequency
  • Break up long methods with extract method into steps at one level of abstraction
  • Break up god classes by grouping methods by the fields and dependencies they use, then extract class
  • Do it behind characterisation tests in small PRs; keep the old public surface as a facade during the move
  • Don't over-split: many tiny classes with one-line methods are just as hard to follow

⏱ 30-second answer

A long method does several jobs at different levels of abstraction: validate, price, save and notify in one 200-line block. A god class is the same problem at class level: an OrderService with 40 methods and 12 dependencies that every feature changes.

They appear by accretion: adding one more if to the existing method is always the cheapest change today.

To break them up:

  • Long method: extract method until the top-level method reads as a list of steps.
  • God class: group methods by the fields and dependencies they use; each cluster is a candidate class (extract class).

The trade-off: split by reason to change, not by line count, or you swap one big class for twenty tiny ones that are just as hard to follow.

🗣 Full answer (senior)

How I would answer this in an interview

"A long method is one that does several things at different levels of abstraction. You can tell because it is hard to name: PlaceOrder that also recalculates loyalty points and sends a Slack alert is really four methods. A god class is the class-level version: one type that knows and does too much, typically a Service or Manager with dozens of public methods, a constructor taking ten or more dependencies, and a file over a thousand lines. Every feature touches it, so it causes merge conflicts and its tests are slow and fragile.

Neither is designed; they grow. Adding a branch to the existing method is always the cheapest change on the day, and in .NET the default project shape encourages it: one OrderService registered in DI becomes the natural home for anything order-related. To recognise them I look at reasons to change rather than lines: if I can list four different stakeholders who would ask for changes to this class, it has four responsibilities. Constructor dependency count is a very good proxy, and CA1502, CA1506 and Sonar's cognitive complexity give numbers.

To break up a long method I extract steps until the top method reads like a recipe, each step at one level of abstraction. For a god class I map which methods use which fields and dependencies; methods that share the same dependencies form clusters, and each cluster becomes a class. I keep the old class as a thin facade that delegates, so callers don't change in the same PR, and I move one cluster per PR behind characterisation tests. The mistake I see is splitting by size: cutting a class into OrderService1 and OrderService2, or into twenty one-line classes. Split by responsibility, or don't split."


How to recognise them

Signal Long method God class
Naming Name needs "and", or is vague (Process, Handle) Vague name: Manager, Helper, Service, Util
Size Doesn't fit on a screen 1,000+ lines, 20+ public members
Dependencies Uses many unrelated locals 8+ constructor parameters
Metrics CA1502 cyclomatic complexity, Sonar S3776 cognitive complexity > 15 CA1506 class coupling, low cohesion (LCOM)
History Long diffs in every change Touched by most PRs; frequent merge conflicts

Breaking them up

Step Long method God class
1. Safety net Characterisation tests on the public method Tests on the public methods you will move
2. Find seams Comment blocks, blank lines and local variables groups mark steps Cluster methods by fields and dependencies used
3. Extract Extract method per step; replace temps with queries Extract class per cluster; inject it
4. Keep callers stable Signature unchanged Old class delegates (facade) until callers move
5. Clean up Inline anything that didn't help Remove the facade method by method

Production example

A common case: a 2,400-line OrderService with 14 constructor dependencies, touched by 70% of PRs. Splitting it by cluster into OrderPricing, OrderPersistence, PaymentCapture and OrderNotifications over about eight PRs typically cuts merge conflicts sharply and lets each new class have fast, focused unit tests.

🔍 What the interviewer is checking

Checks whether the candidate can recognise and safely break up the two most common bloater smells, and knows the over-splitting failure mode.

Green flags

  • Defines both by responsibility and abstraction level, not just size
  • Explains why they grow (accretion, DI makes it cheap)
  • Describes clustering methods by fields/dependencies to find classes
  • Mentions tests first, small PRs and a facade to keep callers stable

Red flags

  • Only uses line counts
  • Proposes a big-bang rewrite
  • Doesn't mention testing or the risk of over-splitting

📚 Learn in depth

1. Levels of abstraction

A readable method stays at one level of abstraction. Compare:

PlaceOrder                     <- level 1: business steps
  Validate(request)
  var priced = Price(request)
  Save(priced)
  Notify(priced)

Price                          <- level 2: pricing detail
  foreach line: unit * qty
  apply discount
  add GST

A long method mixes both levels: business steps interleaved with loops, string formatting and SQL. The reader has to rebuild the structure in their head. Extract method restores it.

2. Why god classes form in .NET

  • DI makes it frictionless. Adding a dependency to a constructor costs one line; nothing pushes back until there are fifteen.
  • Naming by entity. OrderService sounds like the place for everything about orders, so it collects pricing, shipping, refunds and reporting.
  • Fear of new files. People assume a new class needs approval or ceremony.
  • Anaemic entities. When Order has only properties, all behaviour moves to services, which grow.

3. Finding responsibilities with a dependency matrix

List public methods against the fields they use:

                    _db  _tax  _discount  _payments  _email  _sms
PlaceOrder           x    x       x          x         x
CalculateTotal            x       x
ApplyCoupon                       x
Refund               x                       x
SendReceipt                                            x      x
SendDelayNotice                                        x      x

Clusters appear: pricing (_tax, _discount), payments (_payments), notifications (_email, _sms). Each is a candidate class. Methods that use everything, like PlaceOrder, become orchestration that calls the new classes.

4. Metrics, and their limits

  • Cyclomatic complexity counts independent paths (each if, case, &&). CA1502 is off by default; you set a threshold in .editorconfig or CodeMetricsConfig.txt.
  • Cognitive complexity (Sonar S3776) penalises nesting more than flat branches, so it matches how hard code is to read better.
  • Class coupling (CA1506) counts unique types a class depends on.

None of them understands responsibility. A 40-case flat switch scores high and reads fine; a 30-line method mixing three concerns scores low and reads badly.

5. Safe extraction mechanics

IDE refactorings (Visual Studio Extract Method Ctrl+R,M; Rider Ctrl+Alt+M) handle variable capture and ref/out correctly, but they don't know about side effects order, async context or EF change tracking. Move one cluster at a time, run tests after each step, commit often. Keep public signatures stable in the first PR; move callers later.

6. The opposite failure

Over-splitting gives you OrderTotalCalculatorFactoryProvider: one-line methods, five files to follow one flow, and interfaces with one implementation. The goal is cohesion, not small numbers.

Try it yourself

  1. Take your largest service class and build the method-by-field matrix above. How many clusters are there?
  2. Enable CA1502 with a threshold of 15 and CA1506 in .editorconfig; count the hits.
  3. Extract one long method with the IDE refactoring, then check the diff for changed evaluation order.
  4. Count how many PRs in the last quarter touched your biggest class (git log --oneline -- path | wc -l).

💻 Code

Breaking up a long method and starting to split the god class around it, while keeping the public surface stable.

// Before: one method, four responsibilities, all inside a god class
namespace Shop.Orders.Before;

public class OrderService(ShopDbContext db, IPaymentGateway payments, IEmailSender email,
    ITaxTable tax, IDiscountRules discounts /* ...9 more */)
{
    public async Task<Guid> PlaceOrder(PlaceOrderRequest r, CancellationToken ct)
    {
        if (r.Lines.Count == 0) throw new ValidationException("No lines");
        // ...30 more lines of validation
        decimal total = 0;
        foreach (var l in r.Lines) total += l.UnitPrice * l.Quantity;
        total -= discounts.For(r.CouponCode, total);
        total += tax.GstFor(total, r.Country);
        // ...40 lines of persistence, payment and email
        return Guid.NewGuid();
    }
    // ...39 other public methods
}
// After step 1-2: extracted, cohesive classes; OrderService orchestrates
namespace Shop.Orders.After;

public sealed class OrderPricing(ITaxTable tax, IDiscountRules discounts)
{
    public decimal Total(PlaceOrderRequest r)
    {
        var subtotal = r.Lines.Sum(l => l.UnitPrice * l.Quantity);
        var afterDiscount = subtotal - discounts.For(r.CouponCode, subtotal);
        return afterDiscount + tax.GstFor(afterDiscount, r.Country);
    }
}

public sealed class OrderService(
    OrderValidator validator, OrderPricing pricing, OrderStore store,
    PaymentCapture payment, OrderNotifications notifications)
{
    // Reads as a list of business steps at one level of abstraction
    public async Task<OrderId> PlaceOrder(PlaceOrderRequest request, CancellationToken ct)
    {
        validator.EnsureValid(request);
        var total = pricing.Total(request);
        var orderId = await store.SaveAsync(request, total, ct);
        await payment.CaptureAsync(orderId, total, ct);
        await notifications.SendConfirmationAsync(orderId, ct);
        return orderId;
    }
}
// Program.cs: register the extracted classes
builder.Services.AddScoped<OrderValidator>();
builder.Services.AddScoped<OrderPricing>();
builder.Services.AddScoped<OrderStore>();
builder.Services.AddScoped<PaymentCapture>();
builder.Services.AddScoped<OrderNotifications>();
builder.Services.AddScoped<OrderService>();

⚠ Common mistakes

  • Mistake: Splitting by line count (OrderServicePart1, OrderServicePart2). Why it is wrong: Both halves still mix responsibilities and now you have two god classes. Instead: Split by clusters of methods that share fields and reasons to change.
  • Mistake: Extracting methods with names like Step1 or DoStuff. Why it is wrong: It hides the code without explaining it. Instead: Name each extracted method for what it achieves in business terms.
  • Mistake: Breaking up a god class in one big PR. Why it is wrong: Unreviewable, conflicts with everyone, high risk. Instead: Move one cluster per PR and keep a delegating facade until callers migrate.
  • Mistake: Refactoring without characterisation tests. Why it is wrong: Extraction can change evaluation order or swallow exceptions. Instead: Pin current behaviour first, including odd edge cases.
  • Mistake: Over-splitting into many one-line classes with interfaces. Why it is wrong: Following one flow now needs ten files. Instead: Aim for cohesion; inline extractions that didn't help.
  • Mistake: Hiding dependencies to make the constructor look small (service locator, IServiceProvider). Why it is wrong: The class is still a god class, just less honest. Instead: Treat a long constructor as the signal it is and split the class.
  • Mistake: Trusting complexity metrics alone. Why it is wrong: A flat lookup switch scores high and is fine. Instead: Use metrics to find candidates and read the code to decide.

🏛 Senior insight: trade-offs

The senior insight is that god classes are an organisational smell as much as a code one: they sit where team boundaries and domain boundaries are unclear. Splitting OrderService well usually means discovering the real sub-domains (pricing, fulfilment, payments) and is the first step towards modular boundaries, so I involve the people who own those areas. To stop the class regrowing, I get team agreement on ownership: which module owns new behaviour, written down in an ADR, backed by an architecture test, and discussed in reviews and retros so the whole team, not just me, recognises the smell early.

I also know when to stop. A 600-line class that changes twice a year is not worth the risk. I measure: PRs touching the file, merge conflicts, test runtime and defects linked to it, before and after.

Option When it fits Cost When not to
Extract method only Long method, class is otherwise cohesive Minutes, low risk When the method's steps belong to different classes
Extract class by cluster God class with clear method-field clusters Several PRs, facade period Class rarely changes
Split into modules/bounded contexts Clusters map to separate business areas and teams Weeks, needs agreement on boundaries Small codebase or single team
Leave it Stable, low change rate None It sits in the hotspot list

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes extracting steps from a long method Why: Checks whether they can walk through a concrete review and refactoring of a 300-line method
    How to answer

    I'd review it by severity, not by line order. The 300 lines are the least of the problems: the method charges the card before saving the order with no idempotency key, so a timeout and retry can double charge and a crash after charging leaves money taken with no order. It sends email inline and swallows exceptions with an empty catch, so failures vanish. It reads DateTime.Now and multiplies by a magic 1.1.

    Those are blocking comments. Readability is a suggestion with a plan: first add characterisation tests, then make small behaviour-preserving PRs (guard clauses, Extract Method per step, then Extract Class per responsibility), keeping correctness fixes in separate PRs. The trade-off is speed: a big-bang rewrite looks faster but hides behaviour changes in a diff nobody can review.

  2. When: Candidate mentions extract class or IDE refactorings Why: Checks the mechanics of extract method and extract class and what IDE refactorings can still break
    How to answer

    Extract Method takes a block that does one identifiable thing and gives it a name: variables the block reads become parameters, a variable it writes and the caller uses becomes the return value. Extract Class moves a cohesive group of fields and methods (for example, all the GST logic) into a new type that the original class delegates to.

    IDE refactorings (Visual Studio's Extract Method, Rider's Extract Method and Extract Class) work on Roslyn's semantic model, so they find every real reference and compute parameters correctly. They can still surprise you: several written variables produce out parameters, async and lambdas need care, and reflection, JSON names or DI-by-convention are invisible to them.

    The trade-off: extraction helps when the new name says more than the code; extracting single lines just adds jumps.

  3. When: Candidate talks about reasons to change Why: Checks that they connect god classes to the Single Responsibility Principle without over-splitting
    How to answer

    SRP says a module should have one reason to change, which Robert C. Martin later phrased as "responsible to one actor": one group of people whose requests drive its changes. It is not "a class does one thing" or "one method per class". In .NET I look for classes that change for unrelated reasons, such as an OrderService that holds pricing rules (finance), email templates (marketing) and SQL (DBA), and split along those change drivers. I stop splitting when the pieces would always change together, because that is just scattering one responsibility across files.

🛠 Real-world problems: how you handle them

Breaking up a 2,400-line OrderService that every PR touched
Situation
An order management API for [a retailer], [8] developers in [two] teams. `OrderService` was [2,400] lines with [14] constructor dependencies and [41] public methods; almost every feature needed changes to it.
Signals
Merge conflicts in `OrderService.cs` on most PRs; its test class took [90] seconds because it built a full DbContext and mocks for all dependencies; sprint retros repeatedly mentioned 'touching OrderService' as risky; [3] of the last [10] production defects traced back to it.
Investigation
Counted commits per file with `git log --name-only` ([70%] of PRs touched the file). Ran Visual Studio code metrics (class coupling [68], maintainability index [12]). Built a method-by-dependency matrix in a spreadsheet, which showed four clusters: pricing, persistence, payment capture and notifications. Checked existing test coverage of the public methods with coverlet.
Resolution
Added characterisation tests for the [six] most-used public methods. Then over [eight] PRs extracted one cluster per PR into `OrderPricing`, `OrderStore`, `PaymentCapture` and `OrderNotifications`, with `OrderService` delegating to them so callers did not change. Finally moved callers to the new classes and removed the delegating methods.
Prevention
Enabled CA1506 at warning with a threshold, added an architecture test (NetArchTest) limiting constructor parameters on services to [7], and added a PR checklist item asking which class owns new behaviour. Wrote an ADR describing the new module boundaries.

How to tell it (STAR)

**S:** At [company] our `OrderService` had grown to [2,400] lines with [14] dependencies, and [70%] of PRs touched it, so we had constant merge conflicts and it was behind [3] recent defects. **T:** I offered to break it up without stopping feature work. **A:** I mapped which methods used which dependencies and found four clear clusters. I added characterisation tests on the main public methods, then extracted one cluster per PR, leaving `OrderService` as a facade so no callers changed. Once all four were out, we moved callers and removed the facade methods. I added an architecture test limiting service constructor size. **R:** Over [six] weeks and [eight] small PRs we split it with no incidents; merge conflicts on that area dropped [from most PRs to rare], and the new classes' tests ran in [under 2] seconds.

More in Code Smells

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me