<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Salih Erikci on Medium]]></title>
        <description><![CDATA[Stories by Salih Erikci on Medium]]></description>
        <link>https://medium.com/@slh.rkc?source=rss-54b640443f09------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aPkoiArdE5AIYjpZ</url>
            <title>Stories by Salih Erikci on Medium</title>
            <link>https://medium.com/@slh.rkc?source=rss-54b640443f09------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:55:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@slh.rkc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Large Classes Are a Symptom, Not the Disease]]></title>
            <link>https://medium.com/@slh.rkc/why-large-classes-are-a-symptom-not-the-disease-cb49a696be6e?source=rss-54b640443f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb49a696be6e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[god-class]]></category>
            <dc:creator><![CDATA[Salih Erikci]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 13:19:58 GMT</pubDate>
            <atom:updated>2026-08-16T13:28:15.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xN57Tx-X_AHL83h27xi6Vg.png" /></figure><p>Large classes are easy to blame. When a developer opens a file with two thousand lines, dozens of methods, and a constructor full of dependencies, the instinctive reaction is often: this class is too big. But size alone is rarely the real problem. A large class is usually the visible result of deeper design issues — responsibilities that were never separated, concepts that were never given a name, or an architecture that gradually allowed unrelated behavior to accumulate in one place. Splitting such a class into smaller files may make the code look cleaner, but it does not necessarily make the design better. Before asking how to make a class smaller, we should first ask a more important question: why did this class need to know and do so much in the first place?</p><h3>The 2,000-Line Class Isn’t the Real Problem</h3><p>A class with two thousand lines of code immediately attracts attention. It is difficult to navigate, harder to review, and usually unpleasant to modify. Because of that, size becomes the obvious target of criticism. The natural reaction is to split the class into smaller ones and consider the problem solved.</p><p>But line count is only a symptom.</p><p>Martin Fowler’s definition of a code smell almost perfectly expresses the thesis:</p><blockquote><strong><em>“A code smell is a surface indication that usually corresponds to a deeper problem in the system.”</em></strong><em><br> — Martin Fowler</em></blockquote><p>A class can be large and still have a clear, cohesive responsibility. Likewise, a class with only a few hundred lines can be poorly designed if it mixes unrelated concerns, depends on many different parts of the system, or changes for completely different reasons.</p><p>Consider a class like this:</p><pre>public class OrderService {<br>    public Order createOrder(...) { ... }<br>    public BigDecimal calculatePrice(...) { ... }<br>    public void processPayment(...) { ... }<br>    public void createShipment(...) { ... }<br>    public void sendConfirmationEmail(...) { ... }<br>    public void cancelOrder(...) { ... }<br>    public void refundPayment(...) { ... }<br>    public Invoice generateInvoice(...) { ... }<br>}</pre><p>The problem here is not that the class has crossed some arbitrary line-count threshold. Even if each method were only twenty lines long, the design question would remain the same: <strong>why is one class responsible for pricing, payment, shipping, notifications, invoicing, and cancellation?</strong></p><p>This is why metrics such as lines of code should be treated as warning signals rather than design rules. A large class tells us where to investigate, but it does not tell us what the underlying problem is.</p><p>Simply extracting pieces of the class can even make things worse:</p><pre>OrderService<br>OrderServiceHelper<br>OrderServiceUtils<br>OrderServiceProcessor</pre><p>The original file is now smaller, but the responsibilities are still unclear. The complexity has merely been distributed across several files.</p><p>A useful refactoring should reveal meaningful boundaries:</p><pre>OrderService<br>PricingPolicy<br>PaymentProcessor<br>ShipmentPlanner<br>InvoiceGenerator<br>OrderNotificationService</pre><p>Now each component represents a concept or responsibility that can be understood independently.</p><p>The important distinction is therefore between <strong>physical size</strong> and <strong>conceptual size</strong>. Physical size is easy to measure: lines, methods, fields, dependencies. Conceptual size is harder to quantify, but much more important. It describes how many different responsibilities a developer must keep in mind to understand the class.</p><p>A 1,500-line parser implementing one well-defined protocol may be large but cohesive. A 400-line service that contains pricing rules, database access, notification logic, and authorization decisions may be much more problematic.</p><p>The practical benefit of cohesion is cognitive. As Steve McConnell writes in <em>Code Complete</em>, “Carefully defined objects separate concerns so that you can focus on one thing at a time.” A class becomes difficult not merely when it contains many lines, but when understanding it requires keeping several unrelated concepts in your head simultaneously.</p><p>So when encountering a very large class, the first question should not be:</p><blockquote><em>“How can we split this into smaller classes?”</em></blockquote><p>It should be:</p><blockquote><strong><em>“How many distinct responsibilities and reasons to change are hiding inside this class?”</em></strong></blockquote><p>Class size guides us toward the problem. Cohesion, responsibility, and ownership tell us what the problem actually is.</p><h3>Size vs. Cohesion</h3><p>When developers talk about large classes, they often focus on measurable properties: Number of lines, number of methods, number of fields, or constructor size. These metrics are useful because they are easy to observe, but they do not tell us whether a class is well designed.</p><p>A more important property is <strong>cohesion</strong>.</p><p>Cohesion describes how strongly the responsibilities inside a class belong together. A highly cohesive class contains behavior and data that contribute to the same purpose. A low-cohesion class groups together operations that happen to be related only by convenience, naming, or shared access to the same object.</p><p>Consider these two classes:</p><pre>public class CsvParser {<br>    public Header parseHeader(...) { ... }<br>    public List&lt;Row&gt; parseRows(...) { ... }<br>    public Field parseField(...) { ... }<br>    public void validateDelimiter(...) { ... }<br>    public ParsedDocument parse(...) { ... }<br>    // many more parsing-related methods<br>}</pre><p>and:</p><pre>public class CustomerService {<br>    public void updateAddress(...) { ... }<br>    public BigDecimal calculateDiscount(...) { ... }<br>    public void sendSms(...) { ... }<br>    public Invoice generateInvoice(...) { ... }<br>    public boolean checkCreditRisk(...) { ... }<br>    public void terminateContract(...) { ... }<br>}</pre><p>The first class may eventually become much larger than the second. Yet its methods still are related to one clear responsibility: parsing CSV documents.</p><p>The second class may contain fewer lines of code, but understanding it requires knowledge of customer management, discounts, messaging, billing, credit risk, and contracts.</p><p>The difference is not physical size. It is <strong>conceptual distance between the things inside the class</strong>.</p><p>A useful way to think about cohesion is to ask:</p><blockquote><strong><em>If I describe this class in one sentence, can I do so without using the word “and” or commas repeatedly?</em></strong></blockquote><p>For CsvParser, the answer might be:</p><blockquote><em>“This class parses and validates CSV input.”</em></blockquote><p>For the CustomerService, the description quickly becomes:</p><blockquote><em>“This class manages customers, calculates discounts, sends messages, generates invoices, checks credit risk, and manages contracts.”</em></blockquote><p>The second description is already telling us something about the design.</p><h3>Methods Should Need Similar Knowledge</h3><p>Another way to detect cohesion is to look at what different methods need in order to do their work.</p><p>Suppose a service has the following dependencies:</p><pre>public class CustomerService {<br>    private final CustomerRepository customerRepository;<br>    private final CampaignRepository campaignRepository;<br>    private final BillingClient billingClient;<br>    private final CreditScoreClient creditScoreClient;<br>    private final SmsClient smsClient;<br>    private final ContractRepository contractRepository;<br>}</pre><p>Now imagine that:</p><pre>updateAddress()<br>    → CustomerRepository<br>calculateDiscount()<br>    → CustomerRepository<br>    → CampaignRepository<br>generateInvoice()<br>    → BillingClient<br>checkCreditRisk()<br>    → CreditScoreClient<br>sendSms()<br>    → SmsClient<br>terminateContract()<br>    → ContractRepository</pre><p>Most methods use completely different parts of the class.</p><p>This is an important signal. Although the methods live in the same file, they have very little relationship with one another.</p><p>A cohesive class usually has significant overlap in the state, dependencies, and concepts used by its methods. If different groups of methods operate on completely different dependencies, there may be several responsibilities hiding inside the class.</p><p>Conceptually, the class may already look like this:</p><pre>CustomerService<br>    |<br>    ├── CustomerProfile<br>    │      └── CustomerRepository<br>    |<br>    ├── CustomerDiscount<br>    │      └── CampaignRepository<br>    |<br>    ├── CustomerBilling<br>    │      └── BillingClient<br>    |<br>    ├── CustomerRisk<br>    │      └── CreditScoreClient<br>    |<br>    └── CustomerCommunication<br>           └── SmsClient</pre><p>The code simply has not acknowledged those boundaries yet.</p><h3>Shared Data Does Not Automatically Mean Shared Responsibility</h3><p>A common reason for low-cohesion classes is that developers group behavior around a central entity.</p><p>For example, all of these operations involve an Order:</p><pre>calculateOrderPrice(order);<br>checkOrderFraud(order);<br>sendOrderEmail(order);<br>generateOrderInvoice(order);<br>scheduleOrderShipment(order);</pre><p>It is tempting to conclude that they therefore belong in OrderService.</p><p>But the fact that several operations receive an Order does not mean they represent the same responsibility.</p><p>An order is simply the common data they operate on.</p><p>The same reasoning would allow almost every feature in an e-commerce system to eventually end up inside OrderService.</p><p>Instead, the responsibilities may be better expressed as:</p><pre>PricingPolicy<br>FraudChecker<br>OrderNotifier<br>InvoiceGenerator<br>ShipmentScheduler</pre><p>Each component still works with orders, but each owns a different concept.</p><p>This distinction is important:</p><blockquote><strong><em>Sharing the same data does not mean sharing the same responsibility.</em></strong></blockquote><h3>Cohesion Is Also About Change</h3><p>Another useful test is to look at how the class changes over time.</p><p>Suppose different business requests modify different parts of CustomerService:</p><pre>Marketing requirement<br>    → calculateDiscount()<br>Accounting requirement<br>    → generateInvoice()<br>Risk requirement<br>    → checkCreditRisk()<br>Communication requirement<br>    → sendSms()<br>Legal requirement<br>    → terminateContract()</pre><p>These methods do not merely perform different tasks. They are influenced by different business concerns and may even be maintained by different parts of the organization.</p><p>That is a strong indication that the class contains multiple independent reasons to change.</p><p>A cohesive class tends to change for related reasons. Its methods evolve together because they represent the same concept.</p><p>This is why cohesion is closely related to the Single Responsibility Principle. The principle is sometimes simplified to:</p><blockquote><em>“A class should do one thing.”</em></blockquote><p>But “one thing” is often too vague to be useful.</p><p>A more practical interpretation is:</p><blockquote><strong><em>A class should group behavior that belongs together and tends to change together.</em></strong></blockquote><h3>Size Still Matters — But as a Signal</h3><p>None of this means that class size is irrelevant.</p><p>A class with 3,000 lines, 70 methods, and 20 dependencies deserves attention. Large size increases navigation cost, makes code review harder, creates more opportunities for conflicts, and increases the amount of context developers must process.</p><p>But size should trigger a question rather than dictate a solution.</p><p>Instead of:</p><blockquote><em>“This class has 2,000 lines, so we must split it.”</em></blockquote><p>ask:</p><blockquote><em>“Has this class become large because one complex responsibility requires substantial implementation, or because several unrelated responsibilities have accumulated here?”</em></blockquote><p>The answer determines the correct refactoring.</p><p>If the class is large but cohesive, extracting arbitrary pieces may only introduce unnecessary indirection.</p><p>If the class is large because several distinct concepts are mixed together, then its size is pointing toward a genuine design problem.</p><p>The goal, therefore, is not to optimize for the smallest possible classes.</p><p>It is to optimize for classes whose contents make sense together.</p><blockquote><strong><em>Size tells us how much code is in a class. Cohesion tells us whether that code belongs there.</em></strong></blockquote><h3>The “Everything About X” Class</h3><p>One of the most common paths to a large class starts with a harmless naming decision.</p><p>A team creates:</p><pre>CustomerService<br>OrderService<br>ProductService<br>AccountService</pre><p>At first, these classes may be perfectly reasonable. The problem appears later, when the name begins to define the boundary.</p><p>If a new requirement involves a customer, it goes into CustomerService.</p><p>If it involves an order, it goes into OrderService.</p><p>If it involves a product, it goes into ProductService.</p><p>Over time, the rule becomes:</p><blockquote><em>“If it is about X, put it in XService.”</em></blockquote><p>This creates what we can call the <strong>Everything About X class</strong>.</p><p>Consider an OrderService that gradually accumulates methods like these:</p><pre>public class OrderService {<br>    public Order createOrder(...) { ... }<br>    public BigDecimal calculatePrice(...) { ... }<br>    public void reserveStock(...) { ... }<br>    public void chargePayment(...) { ... }<br>    public void createShipment(...) { ... }<br>    public void sendConfirmationEmail(...) { ... }<br>    public boolean checkFraud(...) { ... }<br>    public Invoice generateInvoice(...) { ... }<br>    public void cancelOrder(...) { ... }<br>    public void refundOrder(...) { ... }<br>}</pre><p>Every method is related to an order.</p><p>That fact alone makes the class look coherent.</p><p>But “related to an order” is a very weak boundary. Almost the entire checkout lifecycle is related to an order.</p><p>Pricing changes because pricing rules change. Fraud detection changes because risk rules change. Shipping changes because fulfillment processes change. Payment changes because payment providers or policies change. Notifications change because communication requirements change.</p><p>The common noun hides multiple independent responsibilities.</p><h3>Entity-Centered Naming Creates Weak Boundaries</h3><p>Names like OrderService are attractive because they are easy to understand. They give developers an obvious place to look for order-related functionality.</p><p>But they also create almost unlimited room for growth.</p><p>Ask:</p><blockquote><em>“Does this belong in </em><em>OrderService?”</em></blockquote><p>For most order-related features, the answer can easily be yes.</p><p>Now compare that with:</p><pre>OrderPricingService<br>OrderCancellationService<br>OrderFulfillmentService<br>FraudDetectionService<br>InvoiceGenerator<br>OrderNotifier</pre><p>These names impose stronger boundaries.</p><p>If someone tries to add invoice generation logic to OrderPricingService, the mismatch is immediately visible.</p><p>A narrow name acts as a design constraint.</p><p>A broad name acts as permission. This is why naming is not only a readability concern. It can influence the future architecture of the codebase.</p><blockquote><strong><em>Broad names make broad responsibilities feel legitimate.</em></strong></blockquote><h3>A Shared Noun Does Not Guarantee Cohesion</h3><p>Imagine these methods:</p><pre>public void updateCustomerAddress(...) { ... }<br>public BigDecimal calculateCustomerDiscount(...) { ... }<br>public void assessCustomerCreditRisk(...) { ... }<br>public void sendCustomerSms(...) { ... }<br>public void terminateCustomerContract(...) { ... }</pre><p>They all contain the word Customer.</p><p>That does not mean they belong together.</p><p>Their real subjects may be:</p><pre>Customer Profile<br>Pricing<br>Credit Risk<br>Communication<br>Contract Lifecycle</pre><p>This is an important distinction because developers often judge cohesion at the wrong level.</p><p>They ask:</p><blockquote><em>“Are all these methods about customers?”</em></blockquote><p>A better question is:</p><blockquote><strong><em>“What business capability does each method belong to?”</em></strong></blockquote><p>Once that question is asked, the boundaries often become much clearer.</p><h3>“Service” Can Make the Problem Worse</h3><p>The word Service is especially vulnerable to this problem because it says very little about responsibility.</p><p>A class named:</p><pre>OrderValidator</pre><p>has a fairly clear purpose.</p><p>A class named:</p><pre>OrderPriceCalculator</pre><p>also has a clear purpose.</p><p>But:</p><pre>OrderService</pre><p>could mean almost anything.</p><p>The same applies to names such as:</p><pre>Manager<br>Processor<br>Handler<br>Helper<br>Utils</pre><p>These words can be useful in the right context, but when paired with a broad domain noun they often create classes with weak conceptual boundaries.</p><p>For example:</p><pre>CustomerManager<br>CustomerProcessor<br>OrderHandler<br>ProductHelper</pre><p>do not tell us much about what those classes actually own.</p><p>When the name cannot clearly reject a new responsibility, the class is more likely to absorb it.</p><h3>The Problem Often Appears in Mature Systems</h3><p>It is important not to treat entity-centered services as inherently bad.</p><p>For a simple CRUD application, a class like:</p><pre>CustomerService</pre><p>may be completely sufficient.</p><p>There is little value in decomposing a small service into:</p><pre>CreateCustomerService<br>UpdateCustomerAddressService<br>FindCustomerService<br>DeleteCustomerService</pre><p>just to achieve smaller classes.</p><p>The issue appears when the domain grows but the original class boundary does not evolve with it.</p><p>What started as:</p><pre>CustomerService<br>    → basic customer management</pre><p>slowly becomes:</p><pre>CustomerService<br>    ├── Profile management<br>    ├── Campaigns<br>    ├── Discounts<br>    ├── Credit scoring<br>    ├── Notifications<br>    ├── Billing<br>    ├── Contracts<br>    └── Subscriptions</pre><p>At that point, the class name no longer describes one responsibility. It describes a subject area.</p><p>That is a meaningful warning sign.</p><h3>Look for Hidden Capabilities</h3><p>When an Everything About X class appears, the solution is not automatically to create more classes.</p><p>First, look for distinct capabilities hidden inside it.</p><p>For example:</p><pre>OrderService</pre><p>might reveal:</p><pre>OrderPricing<br>PaymentProcessing<br>OrderCancellation<br>OrderFulfillment<br>OrderBilling<br>OrderNotification</pre><p>The important question is whether these concepts have their own:</p><ul><li>rules</li><li>dependencies</li><li>reasons to change</li><li>tests</li><li>business vocabulary</li></ul><p>If they do, they may deserve independent ownership.</p><p>This is very different from mechanically splitting the class by method count.</p><p>Bad decomposition:</p><pre>OrderServicePart1<br>OrderServicePart2<br>OrderServiceHelper</pre><p>Meaningful decomposition:</p><pre>PricingPolicy<br>PaymentProcessor<br>FulfillmentService<br>CancellationPolicy<br>InvoiceGenerator</pre><p>The second version gives the code concepts that developers can reason about.</p><h3>A Useful Naming Test</h3><p>One simple diagnostic is to look at the class name and ask:</p><blockquote><strong><em>“What kind of behavior would clearly not belong here?”</em></strong></blockquote><p>For OrderPricingService, many answers are obvious:</p><ul><li>sending emails</li><li>creating shipments</li><li>refunding payments</li></ul><p>For OrderService, the answer is much harder.</p><p>That difficulty itself is useful information.</p><p>A good class name should not only describe what belongs inside the class. It should also help developers recognize what does <strong>not</strong> belong there.</p><p>When a class becomes “everything about X,” the problem is not the noun itself. The problem is that the noun has replaced a meaningful responsibility boundary.</p><blockquote><strong><em>Organizing behavior around an entity is convenient. Organizing behavior around clear responsibilities is what keeps that convenience from turning into a God class.</em></strong></blockquote><h3>Dependencies Reveal Hidden Responsibilities</h3><p>Class size can be misleading, but dependencies often tell a much clearer story.</p><p>Consider a service with a definition like this:</p><pre>public class OrderService {<br>    private final OrderRepository orderRepository;<br>    private final CustomerRepository customerRepository;<br>    private final CampaignRepository campaignRepository;<br>    private final PaymentClient paymentClient;<br>    private final InventoryClient inventoryClient;<br>    private final ShippingClient shippingClient;<br>    private final FraudClient fraudClient;<br>    private final NotificationClient notificationClient;<br>    private final InvoiceService invoiceService;<br>}</pre><p>A class like this is usually treated as a readability problem. Developers may try to reduce the number of parameters, introduce a facade, or hide some dependencies behind another object.</p><p>But the more important question is:</p><blockquote><strong><em>Why does one class need to know about all of these systems?</em></strong></blockquote><p>The constructor may be exposing something deeper about the class design.</p><h3>Dependency Count Is a Signal, Not a Rule</h3><p>There is no magic number of dependencies that makes a class badly designed.</p><p>A class with eight dependencies is not automatically wrong, just as a class with three dependencies is not automatically well designed.</p><p>What matters is the relationship between those dependencies and the behavior of the class.</p><p>Suppose OrderService contains these methods:</p><pre>public BigDecimal calculatePrice(...) { ... }<br>public void checkFraud(...) { ... }<br>public void reserveInventory(...) { ... }<br>public void processPayment(...) { ... }<br>public void createShipment(...) { ... }<br>public void generateInvoice(...) { ... }<br>public void sendConfirmation(...) { ... }</pre><p>Now look at which dependencies those methods use:</p><pre>calculatePrice()<br>    → CustomerRepository<br>    → CampaignRepository<br>checkFraud()<br>    → FraudClient<br>reserveInventory()<br>    → InventoryClient<br>processPayment()<br>    → PaymentClient<br>createShipment()<br>    → ShippingClient<br>generateInvoice()<br>    → InvoiceService<br>sendConfirmation()<br>    → NotificationClient</pre><p>The constructor contains nine dependencies, but most methods use only one or two of them.</p><p>That is an important clue.</p><p>The class may physically be one object, but its methods are operating in mostly independent groups.</p><p>Conceptually, it already contains several smaller responsibilities:</p><pre>OrderService<br>    ├── Pricing<br>    │      ├── CustomerRepository<br>    │      └── CampaignRepository<br>    │<br>    ├── Fraud Detection<br>    │      └── FraudClient<br>    │<br>    ├── Inventory<br>    │      └── InventoryClient<br>    │<br>    ├── Payment<br>    │      └── PaymentClient<br>    │<br>    ├── Shipping<br>    │      └── ShippingClient<br>    │<br>    ├── Billing<br>    │      └── InvoiceService<br>    │<br>    └── Notification<br>           └── NotificationClient</pre><p>The dependency graph is revealing boundaries that the class structure is hiding.</p><h3>Look for Dependency Clusters</h3><p>A useful diagnostic technique is to group methods by the dependencies they use.</p><p>Imagine a class has ten dependencies and twenty methods.</p><p>After inspecting the class, you discover something like this:</p><pre>Methods A, B, C<br>    → dependencies 1, 2, 3<br>Methods D, E<br>    → dependencies 4, 5<br>Methods F, G, H<br>    → dependencies 6, 7<br>Methods I, J<br>    → dependencies 8, 9, 10</pre><p>This is often more interesting than the total number of lines in the class.</p><p>If different groups of methods depend on completely different collaborators, those groups may represent different responsibilities.</p><p>For example:</p><pre>public class CustomerService {<br>    private final CustomerRepository customerRepository;<br>    private final CampaignRepository campaignRepository;<br>    private final CreditScoreClient creditScoreClient;<br>    private final SmsClient smsClient;<br>    private final ContractRepository contractRepository;<br>}</pre><p>Suppose the methods naturally cluster like this:</p><pre>updateProfile()<br>changeAddress()<br>    → CustomerRepository<br>calculateDiscount()<br>checkCampaignEligibility()<br>    → CustomerRepository<br>    → CampaignRepository<br>calculateCreditRisk()<br>    → CreditScoreClient<br>sendRegistrationSms()<br>sendReminderSms()<br>    → SmsClient<br>terminateContract()<br>renewContract()<br>    → ContractRepository</pre><p>These clusters are strong candidates for concepts such as:</p><pre>CustomerProfileService<br>CustomerDiscountService<br>CreditRiskService<br>CustomerNotifier<br>ContractService</pre><p>The important part is not the names themselves. The important part is that the dependencies have exposed distinct areas of responsibility.</p><h3>Constructor Growth Often Follows Responsibility Growth</h3><p>Large constructors rarely appear overnight.</p><p>A class may begin with:</p><pre>public CustomerService(<br>    CustomerRepository customerRepository<br>) { ... }</pre><p>Then a new feature needs campaign data:</p><pre>public CustomerService(<br>    CustomerRepository customerRepository,<br>    CampaignRepository campaignRepository<br>) { ... }</pre><p>Another feature needs an external credit scoring system:</p><pre>public CustomerService(<br>    CustomerRepository customerRepository,<br>    CampaignRepository campaignRepository,<br>    CreditScoreClient creditScoreClient<br>) { ... }</pre><p>Later, notifications are added:</p><pre>SmsClient smsClient</pre><p>Then contracts:</p><pre>ContractRepository contractRepository</pre><p>Then billing:</p><pre>BillingClient billingClient</pre><p>Each additional dependency corresponds to a requirement that was added to the class.</p><p>This means constructor growth can act as a kind of historical record.</p><p>It tells us:</p><blockquote><strong><em>This class has gradually become responsible for interacting with more and more parts of the system.</em></strong></blockquote><p>That does not automatically mean every new dependency should create a new class. But it should make us ask whether the responsibility of the existing class is expanding beyond its original boundary.</p><h3>Dependencies Can Reveal the Direction of Refactoring</h3><p>Suppose we start with:</p><pre>OrderService<br>    ├── OrderRepository<br>    ├── CampaignRepository<br>    ├── PaymentClient<br>    ├── InventoryClient<br>    ├── ShippingClient<br>    └── NotificationClient</pre><p>After examining method usage, we discover the following groups:</p><pre>Pricing<br>    → OrderRepository<br>    → CampaignRepository<br>Payment<br>    → PaymentClient<br>Fulfillment<br>    → InventoryClient<br>    → ShippingClient<br>Notification<br>    → NotificationClient</pre><p>Now the decomposition is not arbitrary.</p><p>We can extract responsibilities based on actual collaboration patterns:</p><pre>OrderPricingService<br>    → OrderRepository<br>    → CampaignRepository<br>PaymentProcessor<br>    → PaymentClient<br>OrderFulfillmentService<br>    → InventoryClient<br>    → ShippingClient<br>OrderNotifier<br>    → NotificationClient</pre><p>An application-level service can still coordinate these components when a use case requires them together:</p><pre>public void placeOrder(...) {<br>    Order order = orderPricingService.createPricedOrder(...);<br>    paymentProcessor.charge(order);<br>    fulfillmentService.reserve(order);<br>    orderNotifier.sendConfirmation(order);<br>}</pre><p>The dependencies have not necessarily disappeared from the system.</p><p>They have been moved closer to the responsibilities that actually need them.</p><p>That is the real improvement.</p><h3>Dependency Type Matters Too</h3><p>The number of dependencies is not the only useful signal. Their <strong>type</strong> matters as well.</p><p>A class that depends on several different technical boundaries:</p><pre>Repository<br>Payment Gateway<br>Message Broker<br>Email Client<br>Cache<br>Remote API</pre><p>may be acting as an application-level coordinator, which can be perfectly reasonable.</p><p>The design becomes more suspicious when that same class also contains detailed pricing rules, validation logic, eligibility decisions, or other domain knowledge. In that case, it is responsible both for <strong>making business decisions</strong> and for <strong>coordinating infrastructure</strong>.</p><p>That combination can be a sign that the class is carrying too much responsibility.</p><blockquote><strong><em>Ask not only how many dependencies a class has, but what kind of knowledge those dependencies force it to own.</em></strong></blockquote><h3>Use Dependency Count as a Conversation Starter</h3><p>Rules such as:</p><blockquote><em>“A class should never have more than five dependencies.”</em></blockquote><p>are attractive because they are simple.</p><p>But they are too mechanical.</p><p>A use-case coordinator may legitimately require several collaborators. Conversely, a class with only three dependencies may still combine unrelated responsibilities.</p><p>A better approach is to treat dependency growth as a reason to investigate.</p><p>When a constructor starts becoming uncomfortable, ask:</p><ul><li>Which methods use each dependency?</li><li>Do the same groups of dependencies repeatedly appear together?</li><li>Are some dependencies used by only one or two methods?</li><li>Do those methods represent their own business capability?</li><li>Does the class coordinate those collaborators, or does it also contain their underlying business logic?</li><li>Would moving a dependency to a more focused class make ownership clearer?</li></ul><p>These questions are far more useful than enforcing an arbitrary constructor parameter limit.</p><p>A large dependency list is therefore similar to a large line count.</p><p>It does not prove that the design is wrong.</p><p>But it tells us where to look.</p><blockquote><strong><em>When different methods depend on different parts of the system, the dependency graph may already be showing us the classes that the code has not yet created.</em></strong></blockquote><h3>Private Methods Can Hide Missing Classes</h3><p>Private methods are usually introduced for a good reason: they make long methods easier to read.</p><p>Instead of this:</p><pre>public void placeOrder(...) {<br>    // validate order<br>    // calculate price<br>    // check inventory<br>    // charge payment<br>    // create shipment<br>    // send notification<br>}</pre><p>we refactor it into:</p><pre>public void placeOrder(...) {<br>    validateOrder();<br>    calculatePrice();<br>    reserveInventory();<br>    processPayment();<br>    createShipment();<br>    sendConfirmation();<br>}</pre><p>This is clearly better at the method level. The flow is easier to understand, each step has a name, and implementation details are hidden.</p><p>But there is a subtle risk:</p><blockquote><strong><em>Extracting private methods can improve readability without improving responsibility boundaries.</em></strong></blockquote><p>The class may still own validation, pricing, inventory, payment, shipping, and notification logic. The complexity has been organized, but it has not necessarily been separated.</p><h3>Private Methods Can Be Unnamed Concepts</h3><p>A useful way to review a large class is to look at its private methods as potential concepts.</p><p>Suppose you see:</p><pre>private BigDecimal calculateCampaignDiscount(...) { ... }<br>private boolean isCustomerEligible(...) { ... }<br>private BigDecimal applyLoyaltyDiscount(...) { ... }<br>private BigDecimal calculateFinalPrice(...) { ... }</pre><p>These methods may not simply be implementation details of OrderService.</p><p>Together, they may represent something more meaningful:</p><pre>PricingPolicy<br>DiscountCalculator<br>CampaignEligibility</pre><p>Likewise:</p><pre>private boolean hasEnoughStock(...) { ... }<br>private Warehouse selectWarehouse(...) { ... }<br>private void reserveItems(...) { ... }</pre><p>may be evidence of a hidden:</p><pre>InventoryAllocator</pre><p>And:</p><pre>private void buildEmail(...) { ... }<br>private String resolveTemplate(...) { ... }<br>private void sendEmail(...) { ... }</pre><p>may indicate an:</p><pre>OrderNotifier</pre><p>Private methods often give names to steps before the design gives names to responsibilities.</p><p>That makes them useful clues during refactoring.</p><h3>Extract Method Is Not the Same as Extract Class</h3><p>This distinction is important.</p><p><strong>Extract Method</strong> improves local readability:</p><pre>public void process() {<br>    validate();<br>    calculate();<br>    persist();<br>}</pre><p>It reduces the amount of detail visible at once.</p><p>But all of the knowledge still belongs to the same object.</p><p><strong>Extract Class</strong> changes ownership:</p><pre>public class OrderService {<br>    private final OrderValidator validator;<br>    private final PricingPolicy pricingPolicy;<br>    private final OrderRepository repository;<br>    public void process(Order order) {<br>        validator.validate(order);<br>        pricingPolicy.apply(order);<br>        repository.save(order);<br>    }<br>}</pre><p>Now validation and pricing are represented as independent responsibilities.</p><p>The difference is not just file organization.</p><p>It is about answering:</p><blockquote><strong><em>Which object should know how this behavior works?</em></strong></blockquote><p>This leads to a useful distinction:</p><blockquote><strong><em>Extract Method reduces visual complexity. Extract Class can reduce conceptual responsibility.</em></strong></blockquote><p>Both are valuable, but they solve different problems.</p><h3>Look for Private Method Clusters</h3><p>A single private method does not justify a new class.</p><p>In fact, aggressively turning every helper method into a separate object usually makes a design worse.</p><p>The more interesting signal is a <strong>cluster</strong> of related private methods.</p><p>For example:</p><pre>private Money calculateBasePrice(...) { ... }<br>private Money applyCampaignDiscount(...) { ... }<br>private Money applyCustomerDiscount(...) { ... }<br>private Money calculateTax(...) { ... }<br>private Money calculateFinalPrice(...) { ... }</pre><p>These methods share the same vocabulary and purpose.</p><p>They may naturally belong in:</p><pre>public class OrderPricing {<br>    public Money calculate(Order order, Customer customer) {<br>        ...<br>    }<br>}</pre><p>Similarly:</p><pre>private boolean canCancel(...) { ... }<br>private boolean hasShipmentStarted(...) { ... }<br>private Money calculateCancellationFee(...) { ... }<br>private void releaseReservation(...) { ... }</pre><p>may indicate a distinct cancellation capability:</p><pre>OrderCancellationService</pre><p>or perhaps:</p><pre>CancellationPolicy</pre><p>depending on the nature of the logic.</p><p>The point is not to count private methods. It is to look for groups that talk about the same concept.</p><h3>Private Methods With Different Dependencies Are Especially Interesting</h3><p>The signal becomes stronger when groups of private methods use different dependencies.</p><p>Consider:</p><pre>private void calculatePrice(...) {<br>    campaignRepository.findCampaign(...);<br>}<br>private void chargePayment(...) {<br>    paymentClient.charge(...);<br>}<br>private void createShipment(...) {<br>    shippingClient.createShipment(...);<br>}<br>private void sendEmail(...) {<br>    notificationClient.send(...);<br>}</pre><p>Each method belongs to a different part of the system.</p><p>If these methods are substantial enough to contain their own rules, keeping them private simply hides those responsibilities inside OrderService.</p><p>The class may effectively contain:</p><pre>OrderService<br>    ├── Pricing<br>    ├── Payment<br>    ├── Shipping<br>    └── Notification</pre><p>even though the source code exposes only one public class.</p><p>Private visibility does not make a responsibility disappear.</p><h3>Beware of the Opposite Extreme</h3><p>There is also a danger in taking this idea too far.</p><p>This:</p><pre>private boolean isValidEmail(String email) { ... }</pre><p>does not necessarily require:</p><pre>EmailValidationService</pre><p>And:</p><pre>private String normalizeName(String name) { ... }</pre><p>does not automatically justify:</p><pre>NameNormalizationProcessor</pre><p>Creating a class for every few lines of code produces excessive indirection and makes simple behavior harder to follow.</p><p>A private method should remain private when it is truly an implementation detail of the class’s main responsibility.</p><p>The question is not:</p><blockquote><em>“Could this method technically be moved elsewhere?”</em></blockquote><p>Almost every method could.</p><p>The better question is:</p><blockquote><strong><em>“Does this method represent knowledge that deserves independent ownership?”</em></strong></blockquote><p>That usually depends on whether the behavior has its own rules, vocabulary, dependencies, lifecycle, tests, or reasons to change.</p><h3>A Useful Refactoring Test</h3><p>When reviewing a large class, select a group of private methods and imagine extracting them.</p><p>If the resulting class would have a meaningful name such as:</p><pre>PricingPolicy<br>CreditRiskEvaluator<br>ShipmentPlanner<br>DiscountCalculator<br>ContractTerminationPolicy</pre><p>that is a useful signal.</p><p>If the best name you can find is:</p><pre>OrderHelper<br>OrderUtils<br>OrderProcessor<br>CommonFunctions</pre><p>the extraction may not represent a real responsibility.</p><p>This gives us a simple test:</p><blockquote><strong><em>If the extracted behavior has a clear concept, it may deserve a class. If it only has a technical grouping, keeping it private may be better.</em></strong></blockquote><h3>The Goal Is Better Ownership, Not More Files</h3><p>Private methods are not a code smell by themselves. They are one of the most useful tools for keeping implementation details readable.</p><p>The smell appears when a large class contains many groups of private methods that each encode their own area of knowledge.</p><p>At that point, the class may look organized internally while still being conceptually overloaded.</p><p>A useful way to think about it is:</p><p>Before:</p><pre>OrderService<br>    ├── calculateBasePrice()<br>    ├── applyCampaignDiscount()<br>    ├── applyTax()<br>    ├── authorizePayment()<br>    ├── retryPayment()<br>    ├── selectCarrier()<br>    ├── calculateDeliveryDate()<br>    └── sendConfirmation()</pre><p>After discovering responsibilities:</p><pre>OrderService<br>    ├── PricingPolicy<br>    ├── PaymentProcessor<br>    ├── ShipmentPlanner<br>    └── OrderNotifier</pre><p>The goal is not to eliminate private methods.</p><p>It is to recognize when those methods are doing more than hiding implementation details.</p><blockquote><strong><em>Sometimes a private method is just a private method. But sometimes a group of private methods is a class that has not been named yet.</em></strong></blockquote><h3>Large Classes as Evidence of Missing Domain Concepts</h3><p>Sometimes a class becomes large not because developers failed to split responsibilities, but because the codebase does not yet have the vocabulary needed to represent them.</p><p>Consider a service containing logic like this:</p><pre>public class OrderService {<br>  public BigDecimal calculatePrice(Order order, Customer customer) {<br>        BigDecimal price = order.getBasePrice();<br>        if (customer.isPremium()) {<br>            price = price.multiply(new BigDecimal(&quot;0.90&quot;));<br>        }<br>        if (order.hasCampaign()) {<br>            price = applyCampaignDiscount(order, price);<br>        }<br>        if (customer.getTotalSpend().compareTo(PREMIUM_THRESHOLD) &gt; 0) {<br>            price = applyLoyaltyDiscount(price);<br>        }<br>        return price;<br> }<br>  public boolean canCancel(Order order) {<br>        return order.getStatus() != SHIPPED<br>            &amp;&amp; !order.isAlreadyCancelled();<br>  }<br>  public BigDecimal calculateCancellationFee(Order order) {<br>        ...<br>  }<br>  public boolean isEligibleForFreeShipping(Order order, Customer customer) {<br>        ...<br>  }<br>}</pre><p>At first glance, the obvious problem is that OrderService contains too much logic.</p><p>But simply moving each method into another service may miss the more interesting issue.</p><p>The code is talking about concepts that do not yet exist explicitly in the model:</p><pre>Pricing Policy<br>Loyalty Discount<br>Campaign Eligibility<br>Cancellation Policy<br>Shipping Eligibility</pre><p>Those concepts are present in the business, but only indirectly represented through conditionals, calculations, and private methods.</p><p>The large class is where this missing vocabulary accumulates.</p><h3>Business Rules Often Start as Conditionals</h3><p>Many domain concepts first appear as small pieces of logic:</p><pre>if (customer.getType() == PREMIUM) {<br>    discount = 0.10;<br>}</pre><p>Later another rule is added:</p><pre>if (customer.getTotalSpend() &gt; 100_000) {<br>    discount += 0.05;<br>}</pre><p>Then another:</p><pre>if (campaign.isApplicableTo(customer)) {<br>    discount += campaign.getDiscount();<br>}</pre><p>Eventually the service contains a large collection of conditions:</p><pre>if (...) { ... }<br>if (...) { ... }<br>if (...) { ... }<br>if (...) { ... }</pre><p>Each condition may be perfectly understandable on its own. But together they may be telling us that the application has developed a real business concept:</p><pre>PricingPolicy</pre><p>or:</p><pre>DiscountPolicy</pre><p>The problem is not merely that the method is long.</p><p>The problem is that an important idea exists in the business but has no representation in the code.</p><h3>Missing Concepts Increase Conceptual Load</h3><p>When domain concepts are not modeled explicitly, developers have to reconstruct them mentally every time they read the code.</p><p>Suppose someone wants to understand how cancellation works.</p><p>They open OrderService and find:</p><pre>public void cancelOrder(...) { ... }<br>private boolean canCancel(...) { ... }<br>private boolean hasShipmentStarted(...) { ... }<br>private BigDecimal calculateCancellationFee(...) { ... }<br>private boolean requiresRefund(...) { ... }<br>private void releaseInventory(...) { ... }</pre><p>The developer must infer that these methods collectively represent the concept of <strong>order cancellation</strong>.</p><p>The code knows the concept, but only implicitly.</p><p>An explicit model makes that knowledge visible:</p><pre>public class CancellationPolicy {<br>    public boolean canCancel(Order order) {<br>        ...<br>    }<br>    public Money cancellationFee(Order order) {<br>        ...<br>    }<br>    public boolean requiresRefund(Order order) {<br>        ...<br>    }<br>}</pre><p>Now the concept has a name.</p><p>That name is valuable because it compresses knowledge.</p><p>Instead of thinking:</p><blockquote><em>“the combination of these six conditions and helper methods”</em></blockquote><p>a developer can think:</p><blockquote><em>“the cancellation policy.”</em></blockquote><p>This is one of the most important benefits of good abstractions: they reduce the amount of information developers need to hold in their heads at once.</p><h3>Repeated Rules Are Strong Clues</h3><p>Missing domain concepts often become especially visible when the same kind of logic appears in several places.</p><p>For example:</p><pre>if (customer.getAge() &gt;= 18<br>        &amp;&amp; customer.getRiskScore() &lt; 50<br>        &amp;&amp; customer.hasActiveContract()) {<br>    ...<br>}</pre><p>Later, similar logic appears elsewhere:</p><pre>if (customer.hasActiveContract()<br>        &amp;&amp; customer.getRiskScore() &lt; 50<br>        &amp;&amp; !customer.isBlacklisted()) {<br>    ...<br>}</pre><p>And again:</p><pre>if (!customer.isBlacklisted()<br>        &amp;&amp; customer.getAge() &gt;= 18<br>        &amp;&amp; customer.getRiskScore() &lt; 50) {<br>    ...<br>}</pre><p>The immediate reaction might be to eliminate duplication by extracting a method.</p><pre>private boolean isEligible(Customer customer) {<br>    ...<br>}</pre><p>That is an improvement.</p><p>But the question should go further:</p><blockquote><strong><em>Eligible for what?</em></strong></blockquote><p>If eligibility is an important business concept, perhaps it deserves something like:</p><pre>CampaignEligibilityPolicy<br>CreditEligibilityPolicy<br>SubscriptionEligibility</pre><p>A vague helper method removes duplication.</p><p>A domain concept explains meaning.</p><h3>Large Services Often Contain a Procedural Domain Model</h3><p>This is particularly common in service-heavy architectures.</p><p>The system may have entities that contain little more than state:</p><pre>public class Order {</pre><pre>    private OrderStatus status;<br>    private BigDecimal total;<br>    private Customer customer;</pre><pre>    // getters and setters<br>}</pre><p>while all meaningful behavior lives inside:</p><pre>OrderService</pre><p>The service then contains:</p><pre>if (order.getStatus() == ...) { ... }<br>if (order.getTotal().compareTo(...) &gt; 0) { ... }<br>if (order.getCustomer().getType() == ...) { ... }</pre><p>In effect, the domain model exists as procedural code spread across service methods.</p><p>As the domain becomes more complex, those services grow because every new business rule requires another branch, helper method, or dependency.</p><p>Some behavior may belong directly on the entity:</p><pre>order.cancel();</pre><p>instead of:</p><pre>orderService.validateCancellation(order);<br>order.setStatus(CANCELLED);</pre><p>Other behavior may belong to dedicated domain concepts:</p><pre>cancellationPolicy.canCancel(order);<br>pricingPolicy.calculate(order, customer);<br>eligibilityPolicy.isEligible(customer);</pre><p>The point is not that every system should use a rich domain model.</p><p>For simple CRUD systems, that complexity may be unnecessary.</p><p>But once business rules become substantial, a large service class can be evidence that the domain model is too weak to carry them.</p><h3>Listen to the Vocabulary Used by the Business</h3><p>One of the best sources for discovering missing concepts is the language used by domain experts.</p><p>Suppose business conversations repeatedly include phrases such as:</p><pre>&quot;renewal eligibility&quot;<br>&quot;early cancellation fee&quot;<br>&quot;customer risk category&quot;<br>&quot;loyalty discount&quot;<br>&quot;campaign priority&quot;<br>&quot;delivery promise&quot;</pre><p>But the code contains only:</p><pre>CustomerService<br>OrderService<br>CampaignService</pre><p>plus dozens of conditionals.</p><p>There may be a mismatch between the richness of the business language and the richness of the software model.</p><p>If the business consistently gives something a name, that concept may deserve a name in the code as well.</p><p>For example:</p><pre>RenewalEligibilityPolicy<br>CancellationFee<br>RiskCategory<br>LoyaltyDiscount<br>CampaignPriority<br>DeliveryPromise</pre><p>This does not mean copying every business term into a class.</p><p>But repeated, meaningful vocabulary is a strong clue that a stable concept exists.</p><h3>Good Extraction Changes the Language of the Code</h3><p>A useful way to judge a refactoring is to compare how the code reads before and after.</p><p>Before:</p><pre>if (customer.getTotalSpend() &gt; threshold<br>        &amp;&amp; customer.getType() == PREMIUM<br>        &amp;&amp; !campaign.isExpired()) {<br>    price = price.multiply(discountRate);<br>}</pre><p>After:</p><pre>if (campaignEligibility.isSatisfiedBy(customer, campaign)) {<br>    price = discountPolicy.apply(price, customer, campaign);<br>}</pre><p>The second version is not automatically better because it has more classes.</p><p>It is better only if CampaignEligibility and DiscountPolicy are meaningful concepts that the system actually needs to reason about.</p><p>When they are, the code becomes closer to the language of the problem.</p><p>That is more valuable than simply reducing the number of lines inside OrderService.</p><h3>Avoid Inventing Concepts Just to Make Classes Smaller</h3><p>There is an important danger here.</p><p>Once developers start looking for hidden concepts, it is easy to over-model the system.</p><p>A simple method:</p><pre>private BigDecimal addTax(BigDecimal value) {<br>    return value.multiply(TAX_RATE);<br>}</pre><p>does not necessarily justify:</p><pre>TaxCalculationStrategyFactory</pre><p>Likewise, three small conditions do not automatically require a new policy hierarchy.</p><p>A domain concept should earn its existence.</p><p>Useful signals include:</p><ul><li>the business has a clear name for it,</li><li>it contains meaningful rules,</li><li>it changes independently,</li><li>it appears in several use cases,</li><li>developers repeatedly need to reason about it,</li><li>it has invariants that should be protected,</li><li>or extracting it makes ownership substantially clearer.</li></ul><p>The goal is not to turn every block of logic into an object; the goal is to make important ideas explicit.</p><h3>A Practical Diagnostic Checklist</h3><p>When you encounter a large class, the worst first reaction is often:</p><blockquote><em>“We need to split this.”</em></blockquote><p>Splitting may eventually be the right decision, but it should come after understanding why the class became large.</p><p>A better approach is to treat the class as evidence and investigate what it is telling you.</p><p>The following questions can help.</p><h3>1. Can You Describe the Class in One Clear Sentence?</h3><p>Try to explain the responsibility of the class without referring to its implementation.</p><p>For example:</p><blockquote><em>“This class calculates prices for orders.”</em></blockquote><p>is reasonably precise.</p><p>Compare that with:</p><blockquote><em>“This class manages orders, calculates prices, handles payments, creates shipments, processes cancellations, and sends notifications.”</em></blockquote><p>The repeated use of “and” is often a useful warning sign.</p><p>If the only description you can produce is:</p><blockquote><em>“It handles everything related to customers.”</em></blockquote><p>then the class probably has a subject, but not a clear responsibility.</p><h3>2. Do the Methods Belong to the Same Concept?</h3><p>Look through the public and private methods.</p><p>Ask whether they use the same vocabulary and solve closely related problems.</p><p>For example:</p><pre>calculateBasePrice()<br>applyDiscount()<br>calculateTax()<br>calculateFinalPrice()</pre><p>form a fairly cohesive group.</p><p>But:</p><pre>calculatePrice()<br>sendEmail()<br>checkFraud()<br>generateInvoice()<br>terminateContract()</pre><p>do not.</p><p>The question is not whether the methods all operate on the same entity. It is whether they represent the same area of knowledge.</p><h3>3. Do Different Methods Use Different Dependencies?</h3><p>Inspect which dependencies each method actually uses.</p><p>Suppose the class contains:</p><pre>CustomerRepository<br>CampaignRepository<br>BillingClient<br>CreditScoreClient<br>NotificationClient<br>ContractRepository</pre><p>and the methods divide naturally into groups:</p><pre>discount methods<br>    → CampaignRepository<br>risk methods<br>    → CreditScoreClient<br>billing methods<br>    → BillingClient<br>notification methods<br>    → NotificationClient</pre><p>The dependency graph may already be showing you several hidden responsibilities.</p><p>A particularly useful question is:</p><blockquote><strong><em>Are there dependencies that are used by only a small, isolated group of methods?</em></strong></blockquote><p>If so, those methods may belong somewhere else.</p><h3>4. Does the Class Change for Unrelated Reasons?</h3><p>Look at the history of changes to the class.</p><p>Does it change when:</p><pre>marketing changes discount rules,<br>finance changes invoicing,<br>risk changes eligibility rules,<br>operations changes fulfillment,<br>and product changes cancellation behavior?</pre><p>If so, the class is serving several independent areas of the business.</p><p>This is often a stronger signal than the number of methods it contains.</p><h3>5. Are There Groups of Private Methods With Their Own Vocabulary?</h3><p>Look for clusters such as:</p><pre>calculateCancellationFee();<br>canCancel();<br>requiresRefund();<br>releaseReservation();</pre><p>or:</p><pre>calculateBasePrice();<br>applyCampaignDiscount();<br>applyLoyaltyDiscount();<br>calculateTax();</pre><p>These groups may represent concepts such as:</p><pre>CancellationPolicy<br>PricingPolicy</pre><p>Do not automatically extract them. First ask whether the group has meaningful independent ownership.</p><p>If the only name you can invent is:</p><pre>OrderHelper<br>OrderUtils<br>OrderProcessor</pre><p>the boundary may still be unclear.</p><h3>6. Are Important Business Concepts Represented Only as Conditionals?</h3><p>Large classes frequently contain rules like:</p><pre>if (customer.isPremium() &amp;&amp; campaign.isActive()) {<br>    ...<br>}<br>if (order.getStatus() != SHIPPED &amp;&amp; !order.isCancelled()) {<br>    ...<br>}</pre><p>Look at these conditions and ask:</p><blockquote><strong><em>What business rule is this expressing?</em></strong></blockquote><p>Perhaps the code contains concepts that have never been named:</p><pre>CampaignEligibility<br>CancellationPolicy<br>CreditEligibility<br>RenewalPolicy<br>DiscountPolicy</pre><p>The appropriate refactoring may be to introduce a missing concept rather than simply move methods into another class.</p><h3>7. Is the Class Mostly Coordinating, or Does It Also Know How Everything Works?</h3><p>A coordinator may legitimately depend on several components.</p><p>For example:</p><pre>public void placeOrder(...) {<br>    Order order = pricingService.price(...);<br>    paymentService.charge(order);<br>    fulfillmentService.reserve(order);<br>    notificationService.confirm(order);<br>}</pre><p>This class may not be problematic even if it has several dependencies.</p><p>But if it also contains the internal rules for pricing, payment selection, inventory allocation, and notification formatting, then it owns both orchestration and detailed knowledge.</p><p>Ask:</p><blockquote><strong><em>Does this class tell other components what needs to happen, or does it personally know how every step works?</em></strong></blockquote><p>The second case is much more likely to produce a God class.</p><h3>8. Is the Class Large Because the Responsibility Is Complex?</h3><p>Not every large class should be decomposed.</p><p>A parser, compiler component, protocol implementation, or complex algorithm may require substantial code while still representing one cohesive concept.</p><p>Before extracting anything, ask:</p><blockquote><strong><em>If I split this class, will the resulting classes represent clearer responsibilities, or will I simply distribute one responsibility across more files?</em></strong></blockquote><p>If the proposed classes are:</p><pre>ParserPart1<br>ParserPart2<br>ParserHelper</pre><p>the split may provide little value.</p><p>Class size alone is not sufficient justification.</p><h3>9. Is the Class Name Too Broad?</h3><p>Names can reveal weak boundaries.</p><p>Consider:</p><pre>CustomerService<br>OrderManager<br>ProductProcessor<br>CommonService<br>Utils</pre><p>Now ask:</p><blockquote><strong><em>What behavior would clearly not belong in this class?</em></strong></blockquote><p>If almost anything related to the noun could reasonably be added, the boundary may be too broad.</p><p>Compare:</p><pre>OrderService</pre><p>with:</p><pre>OrderPricing<br>CancellationPolicy<br>ShipmentPlanner</pre><p>The latter names make inappropriate responsibilities easier to recognize.</p><h3>Conclusion: Optimize for Cohesion, Not Class Size</h3><p>Large classes are easy to identify because size is visible.</p><p>We can count lines, methods, fields, and dependencies. We can configure static analysis tools to flag files above a certain threshold. We can look at a 2,000-line class and immediately feel that something is wrong.</p><p>But size is only an indicator.</p><p>The more important question is whether the code inside the class <strong>belongs together</strong>.</p><p>A large class may represent one complex but cohesive responsibility. A much smaller class may combine pricing, validation, persistence, communication, and business rules that change independently.</p><p>This is why class size should start an investigation rather than determine the solution.</p><p>When a class becomes large, look for the forces that caused it to grow:</p><ul><li>Are unrelated responsibilities accumulating here?</li><li>Do different groups of methods use different dependencies?</li><li>Does the class change for unrelated business reasons?</li><li>Are private methods hiding independent concepts?</li><li>Are important domain ideas represented only through conditionals?</li><li>Is a broad name such as OrderService allowing almost anything to be added?</li></ul><p>These questions tell us much more than a line count ever could.</p><p>The same principle applies when refactoring.</p><p>Reducing:</p><pre>2,000 lines</pre><p>to:</p><pre>4 × 500 lines</pre><p>is not necessarily an improvement.</p><p>If those four classes are named:</p><pre>OrderService<br>OrderHelper<br>OrderProcessor<br>OrderUtils</pre><p>then the original responsibility problem may still exist, only with more indirection.</p><p>A successful decomposition should make the system easier to reason about:</p><pre>OrderPricing<br>CancellationPolicy<br>PaymentProcessor<br>ShipmentPlanner<br>OrderNotifier</pre><p>The value of these classes is not that they are smaller. It is that each one owns a recognizable concept.</p><p>That distinction is important.</p><blockquote><strong><em>Small classes are not the objective. Clear ownership is.</em></strong></blockquote><p>This also means there is no universal maximum size for a class.</p><p>Rules such as:</p><ul><li>Classes should stay below 300 lines.</li><li>Classes should have fewer than 10 methods.</li><li>Classes should have no more than 5 dependencies.</li></ul><p>can be useful as warning thresholds, but they should not become design laws.</p><p>Once developers optimize directly for the metric, they often satisfy the metric without solving the design problem.</p><p>Instead, optimize for properties that are harder to measure but more valuable:</p><ul><li>methods that belong to the same concept,</li><li>dependencies that support the same responsibility,</li><li>business rules with clear ownership,</li><li>classes that change for related reasons,</li><li>and boundaries that make it obvious where future behavior belongs.</li></ul><p>A well-designed class should make sense as a unit.</p><p>Its name should describe what it owns. Its methods should reinforce that meaning. Its dependencies should be explainable by that responsibility. When a new requirement arrives, it should be reasonably clear whether the requirement belongs there or somewhere else.</p><p>That is cohesion.</p><p>And cohesion is ultimately what makes a codebase easier to understand, change, test, and evolve.</p><p>So the next time you encounter a 2,000-line class, resist the urge to immediately break it apart.</p><p>Do not begin with:</p><blockquote><em>“How can we make this class smaller?”</em></blockquote><p>Begin with:</p><blockquote><strong><em>“Why did all of this code end up in the same class?”</em></strong></blockquote><p>The answer may reveal unclear responsibilities, missing domain concepts, weak boundaries, or even an architectural pattern that repeatedly creates God classes.</p><p>Once the underlying cause is understood, smaller classes may naturally follow.</p><p>But they are a consequence of better design, not the goal itself.</p><blockquote><strong><em>Optimize for cohesion, not class size.</em></strong></blockquote><h3>References</h3><ul><li>Martin Fowler — <em>Refactoring</em></li><li>Steve McConnell — <em>Code Complete</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb49a696be6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decomposing Large Classes (God Classes)]]></title>
            <link>https://medium.com/@slh.rkc/decomposing-large-classes-god-classes-5cad927e474d?source=rss-54b640443f09------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cad927e474d</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Salih Erikci]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 12:51:55 GMT</pubDate>
            <atom:updated>2024-12-14T12:51:55.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cFcnFDJ38_torX3G" /></figure><h3>Introduction</h3><p>Managing complexity is one of the greatest challenges in programming.</p><p>When a project constantly being developed without considering design principles and not refactored at the same speed we end up with some huge classes that do too many things in itself. This will increase the complexity of the class and hence reduce the readability and maintainability. Many developer will have to work on the same class as a result even when they are working on not so related tasks.</p><p>Robert C. Martin, a pioneer in software craftsmanship, highlights that larger classes often violate the Single Responsibility Principle, making them harder to maintain and extend.</p><p>He said “The larger the class, the more likely it is that you have violated the Single Responsibility Principle.” <em>[Robert C. Martin]</em></p><p>Steve McConnell refers the importance of complexity in his famous book as below.</p><p>“Projects fail most often because of poor requirements, poor planning, or poor management. But when projects do fail for reasons that are primarily technical, the reason is often uncontrolled complexity.” <em>[Code Complete 2, Steve McConnell]</em></p><p>Even if our software gets too big and complex we should always aim to keep it simple as much as possible. We can’t run away from complexity but we can deal with it. Brian Kernighan and Steve McConnell put this reality into words beautifully.</p><p>“Good software, like good art, is a balance between complexity and simplicity.” <em>[Brian Kernighan]</em></p><p>“Complexity can be managed, but it cannot be eliminated.” <em>[Steve McConnell, Code Complete 2]</em></p><p>Classes and functions are the most effective tools we have to manage complexity and we should be using these tools carefully and according to their purpose. If a class itself becomes too complex, it loses all the value it promise to handle complexity. So occasionaly we should give a break to code new features and do some refactor to those large classes that have been too complex.</p><p>“Classes and routines are first and foremost intellectual tools for reducing complexity. If they’re not making your job simpler, they’re not doing their jobs.” <em>[Code Complete 2, Steve McConnell]</em></p><p>The Decomposing a needlessly large class will bring more focused classes which are more readable, testable and maintainable. This separation will help developers being able to work different classes rather than all of them working on one large class.</p><h3>2. Symptoms of a Large Class</h3><p>Some of the most common symptoms of large classes includes.</p><ul><li>Having more than 900 lines of code</li><li>Having more than 30 methods. For instance, a CustomerManager class might include unrelated methods like generateInvoice, sendPromotionalEmails, and updateShippingAddress. These loosely related responsibilities are red flags for a large class.</li><li>Doing lots of loosely related thing in a single class</li><li>Having too many properties. “If a class contains more than about seven data members, consider whether the class should be decomposed into multiple smaller classes <em>[Object-Oriented Design Heuristics 1996, Riel].</em></li><li>A single class needs to be modified by several developers at the same time for different tasks.</li><li>When method names start to get longer than 3 words to make it understandable in the long list of methods in a single class. For example think a class named CustomerService and you want to create a metod to save customer order payment method. Method name would probably something like saveOrderPaymentMethod(), but if you wanted to create the same method in a class named CustomerOrderPaymentService it would be just savePaymentMethod(). Seperating classes helps you to set the context too.</li></ul><h3>3. Why Large Classes Emerge</h3><p>In big projects large classes emerge mostly due to</p><ul><li><strong>Lack of clear design.</strong> Without upfront design, developers may start adding features ad hoc, leading to bloated classes.</li><li><strong>Time pressure.</strong> Under tight deadlines, refactoring often takes a back seat, allowing large classes to grow unchecked.</li><li><strong>Feature creep.</strong> As the scope of a project expands, existing classes are modified instead of creating new ones, increasing complexity.</li><li><strong>Urge to code in the fastest way possible.</strong></li></ul><h3>4. Best Practices for Decomposing Large Classes</h3><ul><li><strong>Clean Up the code.</strong> The first step should be cleaning up the class first from unused code pieces.</li><li>Removing commented out codes</li><li>Removing unused functions</li><li>Removing unused properties</li><li><strong>Remove Duplicate Code</strong>. Identifying duplicate code and turning them into functions</li><li><strong>Extract Methods.</strong> Extracting methods to separate responsibilities of each method instead of doing more than one thing in a single method. Usually big classes have lots of very long brain methods that do many things. Usually it is a rule of thumb that a method should be maximum of length of around 200 lines. Although according to some researches longer methods are not more error prone to shorter methods, they lose being understandable as the get longer. <em>[Code Complete 2, How Long Can a Routine Be?, Steve McConnell]</em><br>After extracting methods it will be much easier to group related methods into a new class.</li><li><strong>Group Responsibilities</strong>. Identifying different responsibilities the class handles currently and moving related responsibilities to new classes. <strong>The Single Responsibility Principle</strong> enforces the idea of separating responsibilities to different classes. The originator of this principle Robert C. Martin explains the principle as follows:<br><em>“Gather together the things that change for the same reasons. Separate those things that change for different reasons.”[Robert C. Martin]</em> . This could be domain based responsibilities or simply data manipulation or calculation responsibilities like String formatting, Date formatting, Date duration calculation, mathematical calculations etc. Most important thing to consider is to find related responsibilities and separate them into new classes.</li><li><strong>Test and Iterate</strong>. Ensure the refactored code maintains existing functionality through comprehensive testing.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cad927e474d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>