Hacker News new | ask | show | jobs
by erAck 2830 days ago
Try to "simply follow" when it's nested twelve levels deep.

Anyhow, with both approaches, nested or early return, the reader has to read the function from the beginning (or read back until the relevant part) to grasp when exactly a code portion will be executed. In both cases, all if's are relevant, there's no guessing.

1 comments

when you want to change someone else code, nested blocks lets you know what conditions are needed for each line. when they are gathered at the start you know the condition for the function but for each line you could start a discussion what conditions are necessary and thus make the code atomic (change all by purpose\tests or change none)
you dont reduce nesting by moving all checks to the beginning, you reduce nesting by moving the contents into methods.

if (product.hasPrice){ if (someOtherCondition){ Cart cart = cartService.getCartForCurrentUser(); cartService.addToCart(product,1); } }

to

if(canSellProduct(product)){ addToCurrentCart(product) }