Cleaner complex IF Statements

Writing clean code like Uncle Bob describes can be complicated sometimes. I go through a variety of options in a simple script to understand implications of refactoring.

Cleaner complex IF Statements
Photo by Pankaj Patel / Unsplash

Writing clean code like Uncle Bob describes can be complicated sometimes. So you have this long if statement that's relatively simple in design but ugly to the eyes and somewhat hard to read.

if(
  x1>=img.left&&x1<=img.left+img.current.width&&
  y1>=img.top&&y1<=img.top+img.current.height&&
  x2>=img.left&&x2<=img.left+img.current.width&&
  y2>=img.top&&y2<=img.top+img.current.height
){
  img.scaling = Math.pow(x1-x2,2)+Math.pow(y1-y2,2);
} //end if

What can we do to make it easier to read? We can start by making variables to simplify the name and see if that helps.

let lowerX=img.left,
    upperX=img.left+img.current.width,
    lowerY=img.top,
    upperY=img.top+img.current.height;
    
if(
  x1>=lowerX&&x1<=upperX&&y1>=lowerY&&y1<=upperY&&
  x2>=lowerX&&x2<=upperX&&y2>=lowerY&&y2<=upperY
){
  img.scaling = Math.pow(x1-x2,2)+Math.pow(y1-y2,2);
} //end if

So that's easier to read the if statement immediately and see what it's doing, but is it really any cleaner? It certainly is longer. We know we can't do compound comparison statements.

// this is evaluated as true
13<=21<=14

// because this is what happens

13<=21 === true;
true<=14; //evaluates as true because...
true==14; //because both are truthy values

// and there is no such thing as <== operator where:
true<==14; //checks equals based on type too

Well, let us attempt to make a helper function to make this simpler and see if it makes it easier to read.

number.prototype.between=function between(a,b){
  return this>=a&&this<=b;
};

let lowerX=img.left,
    upperX=img.left+img.current.width,
    lowerY=img.top,
    upperY=img.top+img.current.height;
    
if(
  x1.between(lowerX,upperX)&&
  y1.between(lowerY,upperY)&&
  x2.between(lowerX,upperX)&&
  y2.between(lowerY,upperY)
){
  img.scaling = Math.pow(x1-x2,2)+Math.pow(y1-y2,2);
} //end if

At what point does making code cleaner also make it more complex?

let conditions = [
  x1>=img.left&&x1<=img.left+img.current.width,
  x2>=img.left&&x2<=img.left+img.current.width,
  y1>=img.top&&y2<=img.top+img.current.height,
  y2>=img.top&&y2<=img.top+img.current.height
];

if(conditions.every(r=>r)){
  img.scaling = Math.pow(x1-x2,2)+Math.pow(y1-y2,2);
} //end if

At what point does sacrificing performance become worth it for code readability?