Skip to content

go.halstead_complexity

Maintainability Low

Analyzes Halstead complexity metrics to identify hard-to-maintain functions.

High complexity functions have measurable consequences:

  • More bugs — Studies show defect density increases with complexity
  • Slower development — Takes longer to understand and modify
  • Testing burden — More paths require more test cases
  • Review difficulty — Code reviewers miss issues in complex code

Halstead metrics provide objective measures that correlate with maintenance cost.

  • Difficulty (D) — How hard to write or understand
  • Effort (E) — Mental effort required
  • Volume (V) — Information content
  • Vocabulary (n) — Unique operators and operands
  • Length (N) — Total operators and operands
// ❌ Before (high complexity)
func processOrder(order *Order, user *User, inv *Inventory, pay *Payment) error {
if order.Status != "pending" {
return errors.New("invalid status")
}
if !user.Verified {
return errors.New("user not verified")
}
if user.Balance < order.Total {
return errors.New("insufficient balance")
}
for _, item := range order.Items {
stock, ok := inv.Stock[item.ID]
if !ok || stock < item.Qty {
return fmt.Errorf("item %s out of stock", item.ID)
}
inv.Stock[item.ID] -= item.Qty
if inv.Stock[item.ID] < 10 {
notifyRestock(item.ID)
}
}
if err := pay.Charge(user.ID, order.Total); err != nil {
for _, item := range order.Items {
inv.Stock[item.ID] += item.Qty // Rollback
}
return err
}
order.Status = "complete"
return nil
}
// ✅ After (decomposed)
func processOrder(ctx *OrderContext) error {
if err := validateOrder(ctx.Order, ctx.User); err != nil {
return err
}
reserved, err := reserveInventory(ctx.Order, ctx.Inventory)
if err != nil {
return err
}
if err := processPayment(ctx.User, ctx.Order.Total, ctx.Payment); err != nil {
releaseInventory(reserved, ctx.Inventory)
return err
}
ctx.Order.Status = "complete"
return nil
}
func validateOrder(order *Order, user *User) error {
if order.Status != "pending" {
return errors.New("invalid status")
}
if !user.Verified {
return errors.New("user not verified")
}
if user.Balance < order.Total {
return errors.New("insufficient balance")
}
return nil
}

Each function has a single responsibility and lower complexity.

  • Functions exceeding difficulty threshold
  • High effort scores
  • Deeply nested control flow
  • Long parameter lists

Unfault flags high-complexity functions. Refactoring is manual but guided.