If I have a single if condition I wouldnt spend too much time ruminating about the style. But if I have multiple guard conditions I would prefer style2
Picuture this. Assume that the tests are complex and you really dont want to tie them into a single if-ORed condition to avoid complexity:
//Style1
if (this1 != Right)
{
return;
}
else if(this2 != right2)
{
return;
}
else if(this3 != right2)
{
return;
}
else
{
//everything is right
//do something
return;
}
versus
//Style 2
if (this1 != Right)
{
return;
}
if(this2 != right2)
{
return;
}
if(this3 != right2)
{
return;
}
//everything is right
//do something
return;
Here there are two main advantages
You are separating the code in a single function into two visually logcal blocks : an upper block of validations(guard conditions) and a lower block of runnable code.
If you have to add/remove one condition , you reduce your chances of messing up the entire if-elseif-else ladder.
Another minor advantage is you have one lessfewer set of braces to care for.