Source Lines of Code (SLOC)
Source lines of code is a quantitative metrics that measures the number of lines in the body of a function/method/constructor, excluding blank lines and comments.
To get real-time analysis for this metric, enable the avoid-long-functions rule.
Why Be Cautious
High number of source lines can lead to:
- Reduced Readability: Long methods are harder to understand and follow, especially when they perform multiple actions.
- Maintainability Challenges: Long methods are more complex to update and debug.
- Difficulty in Testing: High SLOC usually indicates a method with too many responsibilities which require more tests.
How to Address High SLOC?
First, understand the responsibility of the method. Depending on that, try breaking down the method into smaller ones by extracting additional logic to dedicated methods. Also, try moving out repeated code (if any) and reusing already existing code.
Remember that small, focused methods are easier to test, understand, update and reuse.
Config Example
dcm:
metrics:
source-lines-of-code:
threshold: 50
To set multiple threshold or other common config options, refer to the Configuring Metrics page.
Example
To view what contributes to the metric value, generate an HTML report.
❌ Bad: High Number of Source Lines
// SLOC: 30
void processOrder(Order order) {
if (order.isPaid) {
if (order.hasStock) {
if (order.isEligibleForDiscount) {
applyDiscount(order);
}
if (order.requiresShipping) {
if (order.isInternational) {
calculateInternationalShipping(order);
} else {
calculateDomesticShipping(order);
}
switch (order.shipping.status) {
case .pending:
...
case .processed:
...
case .failed:
...
case _:
...
}
} else if (order.pickupLocation != null) {
arrangePickup(order);
}
} else {
throw Exception('Out of stock');
}
} else {
logPaymentPending(order);
}
}
✅ Good: Low Number of Source Lines
// SLOC: 9
void processOrder(Order order) {
if (!order.isPaid) {
logPaymentPending(order);
return;
}
if (!order.hasStock) {
throw Exception('Out of stock');
}
applyDiscountIfEligible(order);
processShipping(order);
}
// SLOC: 3
void applyDiscountIfEligible(Order order) {
if (order.isEligibleForDiscount) {
applyDiscount(order);
}
}
// SLOC: 9
void processShipping(Order order) {
if (order.requiresShipping) {
if (order.isInternational) {
calculateInternationalShipping(order);
} else {
calculateDomesticShipping(order);
}
} else if (order.pickupLocation != null) {
arrangePickup(order);
}
}