There are two primary ways to format blocks of code.
I'm used to doing stuff like so:
function do_something() {
if(cond) {
if (cond 2) {
if (cond 3) {
whatever_good();
} else
whatever_bad3();
} else
whatever_bad2();
} else
whatever_bad1();
}
But recently I was introduced to this type of organising code:
function do_something() {
if(!cond) {
whatever_bad1();
return;
}
if (!cond 2) {
whatever_bad2();
return;
}
if (!cond 3) {
whatever_bad3();
return;
}
whatever_good();
}
This second way is more readable, I have to admin. But it just makes me cringe to write code like that... Even tho I realise that the second if probably better. I think I just have to change my habits.
So. My question is: Is there some guidelines on how to structure code in a better way? This may be too broad, but this is something that you can't find easily in google. Especially this particular case for these two ways of writing code. I tried to find comparison of these two ways, but couldn't find even a single article about it. Also maybe some guidelines on improving readability.
So, I would really appreciate some links.
PS - Right now I'm asking this for php, but I think this also works for most other languages. So, this does not have to be necesary sticktly about php.