Adding my two cents.
I found that writing code the way Rick did it is often easier to structure, for instance when having another if
statement or a loop, let me give you an example.
private void MyMethod()
{
if(someCondition)
{
if(!anotherCondition)
{
SomeCode();
}
}
}
An if
statement nested inside another if
statement means that the first condition is actively affecting the first second one, meaning you really need to think your conditions thoroughly to prevent logical errors. I’ve found that sometimes I have to add more conditions or be super careful with the naming to prevent confusion.
private void MyMethod()
{
if(someCondition) { return; }
if(anotherCondition)
{
SomeCode();
}
}
Rick’s method makes it relatively easier to read and makes each condition independent from one another since there’s no nesting, breaking the logic in more steps which is often better, so you don’t have to be as careful with your conditions, it is also, sometimes easier to diagram.
I’m not saying that you shouldn’t nest if
statements, it’s perfectly fine to do that, it’s just a matter of preference, the more you practice, the more you’ll fine your own style, coding is like drawing, there are some bases that you should follow, but once you master those, you can do whatever you want.