Tips for cleaner code: Cleaning up IF statements
1 min readNov 7, 2018
We know that IF statements are very crucial in our
development we can’t really get out of using them.
We are going to apply two very basic rules to just
tidy up the way that we actually use them.
1 — Always return what you’re expecting last
if(firstName == ‘’ && lastName == ‘’)
return null;
if(age < 18)
return null;
return firstName +’ ‘ + lastName;
With this approach we avoid nested ifs
2 — Negate ifs to avoid nesting blocks of if-else
The wrong approach:
if(file)
{
if(array.Leght > 0)
{
// your code are
}
else
{
return;
}
}
else
{
//thrown error redirect
}
The correrct approach:
if(!file){
//trhown error redirect
}if(array.Leght == 0){
//error redirect
}
These are very basic tips, but they avoid a lot of headaches.