Admir Mujkic
2 min readJan 12, 2025

--

Thanks for the feedback.

Let me explain why I diagree and why early returns are often better than using else blocks:

// Hard to cognitively track - need to keep multiple states in mind
function processOrder(order) {
if (order.isValid) {
if (order.hasStock) {
if (order.paymentVerified) {
if (order.shippingAddressValid) {
// At this point, you need to mentally track 4 nested conditions
// to understand how the code got here
processPayment(order);
updateInventory(order);
scheduleShipment(order);
return true;
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}

// Mentally easier to follow - each condition is independent
function processOrder(order) {
// Brain can "discard" this condition once it passes over it
if (!order.isValid) {
return false;
}

// Same case - after checking, brain can "forget" it
if (!order.hasStock) {
return false;
}

// Each condition is standalone and doesn't require remembering previous ones
if (!order.paymentVerified) {
return false;
}

// Final check, also independent
if (!order.shippingAddressValid) {
return false;
}

// We get here with a "clear" mind
// No need to remember complex condition hierarchy
processPayment(order);
updateInventory(order);
scheduleShipment(order);
return true;
}

Additional explanations regarding cognitive load:

1. Mental "Stack"
- In the first version, our brain must maintain a "stack" of conditions
- Each new `if` adds a new state we need to remember
- To understand deeply nested code, we must mentally maintain the entire path

2. Sequential Thinking
- Early returns enable sequential processing
- We can process each condition and "forget" it
- It's easier to think about one thing at a time

3. Clearer Mental Picture
- Code with early returns better matches how people naturally solve problems
- "If something's wrong, stop immediately" is a more natural way of thinking
- It's easier to understand "what can go wrong" when conditions are explicitly listed at the start

4. Maintaining Mental Context
- Less context to keep in working memory
- Easier to debug code because it's clear where and why the function stops
- Simpler to add new conditions because we don't need to think about nesting

5. Focus on Business Logic
- After validations, we can fully focus on the main task
- No need for mental "filtering" through layers of conditions
- Clearer separation between validation and actual business logic

This is especially important for:
- Working on complex functions
- Code review process
- Maintaining legacy code
- Team work where multiple people need to understand the code
- Debugging and finding errors

--

--

Admir Mujkic
Admir Mujkic

Written by Admir Mujkic

I am Admir Mujkić, a technical architect with over 15 years of experience helping businesses harness technology to innovate, grow, and succeed.

Responses (1)