In using ReSharper recently, it is suggesting I reduce nesting in certain places by inverting if conditions and using the continue statements.
nested conditionals:
foreach(....)
{
if(SomeCondition)
{
//do some things
if(SomeOtherNestedCondition)
{
//do some further things
}
}
}
continue statements:
foreach(....)
{
if(!SomeCondition) continue;
//do some things
if(!SomeOtherNestedCondition) continue;
//do some further things
}
I understand some of the logic of why you’d want to reduce nesting for performance and memory issues as well as how the two snippets equate to each other, however from my development background, the before example is easier to follow when reading the code.
Which approach do you prefer and why? Do you use continue over nested ifs in your everyday code?
As a rule I have found it best to always start statement blocks with any conditions that will except out as it reduces complexity, but more importantly throws out non-compatible circumstances before they are stepped any further which can increase code and memory performance. This also ensures safety of your conditions over a duration through maintenance, that it’s less likely to have invalid scenarios passed into code they don’t belong in.
Plus I think the second of the two is more readable personally because you don’t have the scope layers confusing what’s available, it’s easy to create a variable in one layer later down the road and not realize it’s unavailable in another layer, or having to manage them to be modified appropriately etc.
This isn’t just continue in loops, but this also refers to conditions of methods should return; instead of having a method start
it should always start