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.
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:
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.
"A long method is one that does several things at different levels of abstraction. You can tell because it is hard to name:
PlaceOrderthat 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 aServiceorManagerwith 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
OrderServiceregistered 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
OrderService1andOrderService2, or into twenty one-line classes. Split by responsibility, or don't split."
| 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 |
| 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 |
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.
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
Red flags
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.
OrderService sounds like the place for everything about orders, so it collects pricing, shipping, refunds and reporting.Order has only properties, all behaviour moves to services, which grow.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.
if, case, &&). CA1502 is off by default; you set a threshold in .editorconfig or CodeMetricsConfig.txt.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.
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.
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.
.editorconfig; count the hits.git log --oneline -- path | wc -l).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>();
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.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.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.switch scores high and is fine. Instead: Use metrics to find candidates and read the code to decide.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 |
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.
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.
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.
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.
Last updated 23 Nov 2026.