+ 1

Why nested if is not recommended to use in code?

someone told me not to use nested if in coding

21st Jul 2017, 12:35 PM
Shubham Rampurkar
Shubham Rampurkar - avatar
4 Respostas
+ 2
Well that is not 100% acurate. What you don't want to do is over-nest your code to a point where it is hard to read, or your conditions will never be met. In some cases nesting is required and potentially faster if the parent is not going to be true often, since it will not have to check the child conditions.
21st Jul 2017, 12:45 PM
Jim Tully
Jim Tully - avatar
+ 1
it gets really hard to read and understand after a certain number of nested if statements
21st Jul 2017, 12:52 PM
‎ ‏‏‎Anonymous Guy
+ 1
I used to maintain code that had nested if statements all over the place. The depth was anywhere between 2 to 12. Needless to say, the maintenance was a nightmare every time I had to edit the code for fixes or upgrades or both. This was a daily affair. Taking a bird's eye view, the code turned out to be a fully functioning protocol parser and interpreter. I started a new branch to refactor and use abstractions. Within a few weeks the new branch started passing all the tests from the production branch. Then we started writing tests for the refactoring branch. The biggest pain in nested if statements was being unable to fully fathom the code in its entirety. So depending on how badly you want to hold the code in your mind while working on it or how much of it you want to hold there, nested if statements can be a nightmare or benign things. A general rule of thumb is, when you are indenting more than 4 levels deep, step back, refactor the code. You will get many reusable components out of this exercise. If I'm recalling correctly, Linus Torvalds does not allow more than 4 levels deep indentation in the kernel for this reason. He goes so far as to actively kill off if statements and use them sparingly. He calls it bad taste.
21st Jul 2017, 1:28 PM
Venkatesh Pitta
Venkatesh Pitta - avatar
0
Why not? When it is required I do not see reason why shouldn't you.
21st Jul 2017, 12:44 PM
Jakub Stasiak
Jakub Stasiak - avatar