vendredi 20 décembre 2019

Remove if statement

If if statement could be avoided it is considered a good practice.

For example this code:

if (a > 80) {
  a = 80;
}

Can become this:

a = Math.min(80, a);

That way the code is considered cleaner because there is no branch logic.

But is there any way to avoid if for more complex problems like this:

if (array.length > 5) {
   array = array.reverse().join('');
} else {
   array = 'array is lte 5';
}

If array length is > 5 then reverse it and join it, otherwise return "array is lte 5".

This is simple example but more complex than the first example and it's hard to remove if.

How mathematics handle branches and is it possible to express this logic in mathematics.

I can extract it to a separate method but it will only move the if statement in the method itself, it will not remove it.

I can imagine I can use some functions from Ramdajs but i didn't find appropriate one and even if I find one the if will be there i guess - it will be only abstracted.

Also imagine this sudo code:

if (file_exists(file)) {
   content = file_read(file);
   if (content.startsWith('config')) {
       ret = 'config:'; 
   } else if (content.endsWith(':app')) {
       ret = ':app';
   }  
} else {  
   ret = '';
}

This code has only 2 if statements but already is a nightmare to read and change.

Is it possible to use mathematic and/or express it more clearly avoiding branches.

I know in mathematics there is no "read file" but it was just an example.

Thank you

Aucun commentaire:

Enregistrer un commentaire