by vpaulus on 5/11/23, 5:01 AM with 5 comments
I prefer the following way (in controllers, etc.):
function ($param)
{
if ($param is not valid) {
return false
}
// do the stuff
return true;
}
While my coworker does the opposite: function ($param)
{
if ($param is valid) {
// do the stuff
return true;
}
return false
}
We agreed that none of them is good or wrong, just different approach. I am curious, how do you do, what are your thoughts, pros and cons?by armchairhacker on 5/11/23, 6:20 AM
function login() {
if (isLoggedIn) {
return
}
if (!isAuthenticated) {
throw AuthenticationFailure
}
// Do the login
...
}
It doesn't matter that `isLoggedIn` is positive and `isAuthenticated` is negative, the point is both of those are short-circuit cases.Though what usually actually ends up happening is
function login() {
if (isLoggedIn) {
return
} else if (isAuthenticated) {
doTheLogin()
} else {
throw AuthenticationFailure
}
}
function doTheLogin() {
...
}
Where there's no "long case", so the order really doesn't matter and I just make everything positive.by proc0 on 5/11/23, 6:10 AM
by throwaway_5753 on 5/11/23, 5:19 AM
- Quick returns go inside the condition to save a level of nesting in the function; try to minimize level of nesting of the main function body
- I try to return a value at the end of a function that will do the least harm if I somehow fall through (because maybe I've messed up the condition or something), for example:
def launch_nukes():
if you_are_sure():
launch()
abort()
It's not always obvious how best to structure a function to meet the second criteria, but in general I try to think defensively (how to minimize chances of bad bugs both now and when I come back in 6 months).by deofoo on 5/11/23, 7:08 AM
by prudentpomelo on 5/11/23, 6:36 AM