python.halstead_complexity
Maintainability
Low
Analyzes Halstead complexity metrics (difficulty, effort, volume) to identify hard-to-maintain functions.
Why It Matters
Section titled “Why It Matters”Complex functions cause maintenance problems:
- Hard to understand — New developers struggle to grasp the logic
- Bug-prone — More complexity means more places for bugs to hide
- Difficult to test — Complex code needs more test cases
- Risky to change — Modifications have unexpected side effects
Halstead metrics quantify this complexity objectively, helping you prioritize refactoring efforts.
Halstead Metrics Explained
Section titled “Halstead Metrics Explained”- Difficulty (D) — How hard the code is to write or understand
- Effort (E) — Total effort required to implement
- Volume (V) — Size of the implementation
- Vocabulary (n) — Number of unique operators and operands
- Length (N) — Total operators and operands
Example
Section titled “Example”# ❌ Before (high complexity)def process_order(order, user, inventory, payments, shipping): if order.status == 'pending': if user.verified and user.balance >= order.total: for item in order.items: if item.id in inventory and inventory[item.id] >= item.qty: inventory[item.id] -= item.qty if inventory[item.id] < 10: notify_restock(item.id) else: return {'error': 'out_of_stock', 'item': item.id} if payments.charge(user.id, order.total): shipping.schedule(order, user.address) order.status = 'complete' return {'success': True} else: # Rollback inventory... 20 more lines pass return {'error': 'invalid_order'}# ✅ After (decomposed)def process_order(order, user, inventory, payments, shipping): validation_error = validate_order(order, user) if validation_error: return validation_error
inventory_result = reserve_inventory(order, inventory) if not inventory_result.success: return inventory_result.error
payment_result = process_payment(user, order.total, payments) if not payment_result.success: release_inventory(inventory_result.reservations, inventory) return payment_result.error
schedule_shipping(order, user, shipping) return {'success': True}Each extracted function has single responsibility and lower complexity.
What Unfault Detects
Section titled “What Unfault Detects”- Functions with difficulty score above threshold
- Functions with high effort score
- Deeply nested conditionals
- Long parameter lists
Auto-Fix
Section titled “Auto-Fix”Unfault suggests function extraction for high-complexity blocks, but refactoring is manual.