Ask HN: Do you follow the positive or negative pattern when programming?
Me and my coworker follow a totally different pattern while programming. Probably there are a better technical term for that, but I call it now positive pattern and negative pattern.
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?
5 comments
[ 2.1 ms ] story [ 23.2 ms ] thread- 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:
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).Though what usually actually ends up happening is
Where there's no "long case", so the order really doesn't matter and I just make everything positive.