Back to Catalog
Code Smells
Bloaters
Long Method
Methods that are too long and do too many things.
Intent & 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.'
Real-world Use Case
Use when methods exceed 20-30 lines, when they handle multiple responsibilities, or when they’re difficult to understand and test.
Source
📌 TL;DR
Long methods are hard to understand and maintain. Break them into smaller, focused functions. Apply Extract Method refactoring.
Advantages
- Easier to understand and maintain
- Better testability with smaller units
- Improved code reusability
Disadvantages
- Can increase number of methods
- May require careful parameterization
Implementation Example
// 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;
}