Code Quality
Long Python Functions: When They Become a Problem
Functions longer than 20-30 lines tend to do multiple things. They are harder to test, debug, and understand. The Single Responsibility Principle says each function should do one thing.
❌ Overly Long Function
def process_order(order_id, user_id, items, coupon_code):
user = db.get(user_id)
if not user: raise ValueError('User not found')
if not user.is_active: raise ValueError('User suspended')
total = 0
for item in items:
product = db.get_product(item['id'])
if product.stock < item['quantity']:
raise ValueError(f'Insufficient stock')
total += product.price * item['quantity']
if coupon_code:
coupon = db.get_coupon(coupon_code)
if coupon and coupon.is_valid():
total *= (1 - coupon.discount)
order = db.create_order(user_id, total)
send_email(user.email, 'Order confirmed!')
return order✅ Refactored into Functions
def process_order(order_id, user_id, items, coupon_code):
user = validate_user(user_id)
total = calculate_total(items)
total = apply_coupon(total, coupon_code)
order = create_order(user_id, total, items)
notify_user(user.email)
return order
def validate_user(user_id): ...
def calculate_total(items): ...
def apply_coupon(total, coupon_code): ...💡
Pro tip: Each function should do one thing. If you need a comment to explain what a block of code does, extract it into a named function instead.
Paste this code into LearnCodeGuide
Detect Python vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Python Code →