# Long Method

> Methods that are too long and do too many things.

- **Category**: Code Smells
- **Subcategory**: Bloaters
- **Canonical URL**: https://designpattern.fyi/patterns/long-method/

---

## Description
'**Intent**: Identify methods that have grown too large and handle multiple responsibilities. Long methods are hard to understand, test, and maintain.

**Context**: You have methods that span hundreds of lines, with nested logic and multiple responsibilities. Understanding the flow requires significant mental effort, and testing individual pieces is difficult.

**Solution**: Break down long methods into smaller, focused methods. Extract logical blocks into separate methods with descriptive names. Apply Extract Method refactoring repeatedly.'



## Use Cases
Use when methods exceed 20-30 lines, when they handle multiple responsibilities, or when they're difficult to understand and test.



## Implementation Example

```javascript
// Before: Long method
function processOrder(order) {
  // Validate order
  if (!order.customer) {
    throw new Error('Customer required');
  }
  if (!order.items || order.items.length === 0) {
    throw new Error('Items required');
  }
  if (order.total <= 0) {
    throw new Error('Invalid total');
  }

  // Calculate discounts
  let discount = 0;
  if (order.customer.vip) {
    discount += order.total * 0.1;
  }
  if (order.total > 1000) {
    discount += order.total * 0.05;
  }

  // Apply tax
  const tax = (order.total - discount) * 0.08;
  const finalTotal = order.total - discount + tax;

  // Update inventory
  order.items.forEach(item => {
    const product = findProduct(item.productId);
    if (product.stock < item.quantity) {
      throw new Error('Insufficient stock');
    }
    product.stock -= item.quantity;
  });

  // Save order
  const savedOrder = database.save(order);

  // Send confirmation
  emailService.send(order.customer.email, 'Order confirmation');

  return savedOrder;
}
```



## Trade-offs


### Advantages

- Easier to understand and maintain

- Better testability with smaller units

- Improved code reusability




### Considerations & Drawbacks

- Can increase number of methods

- May require careful parameterization







---
**Reference**: [Original Source](https://refactoring.guru/smells/long-method)

