A better way to write this IF statement

Hi there,
I’m very new to processing and I was wondering if there’s a better way to write this IF statement. What I’m doing is creating a drawing tool and want to confine the line to a space in the window. This statement works but I’m guessing there’s a cleaner way to write this out and would love to know how.

Thanks!

    if (mouseX > margin && mouseX < width - margin && mouseY > margin && mouseY < width - margin && pmouseX > margin && pmouseX < width - margin && pmouseY > margin && pmouseY < width - margin) {
      line(pmouseX,pmouseY,0, mouseX,mouseY, 0);
    }
1 Like

if(statements can be written as follows

if(condition){
   someCode();
}

if(condition)someCode();

//note this is best kept to single instructions for the condition as it can fail if you chain more than one instruction and you would then have to encapsulate everything in {}


A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
    result = x;
} else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

1 Like

One thing you might think of is in fame number ‘fn’
mouseX > margin && mouseX < width - margin && mouseY > margin && mouseY < width - margin
is the same as this
pmouseX > margin && pmouseX < width - margin && pmouseY > margin && pmouseY < width - margin
in frame no ‘fn + 1’

So if you have 2 global boolean variables curr and last then this should work

curr = mouseX > margin && mouseX < width - margin && mouseY > margin && mouseY < width - margin;
if ( curr && last) {
      line(pmouseX,pmouseY,0, mouseX,mouseY, 0);
}
last = curr;

Note this reduces the number of boolean conditions to evaluate by half :grinning:

2 Likes

Thank you. That’s really helpful to think of the arguments as variables.

This appears to be code for a button, you could make a method the returns a bool based on if the mouse is in that area.

Example function:

boolean inArea(int X, int Y, int x, int y, int w, int h) {
  if (X > x && Y > y && X < x + w && Y < y + h) {
    return true;
  } else {
    return false;
  }
}

For this case just put
if(inArea(mouseX,mouseY,rectX,rectY,rectWidth,rectHeight)){}
if this is code for a button add mousePressed to that

2 Likes

If you want you can separate each logic statement in the if() By a line break:

if (mouseX > margin 
&& mouseX < width - margin 
&& mouseY > margin 
&& mouseY < width - margin 
&& pmouseX > margin
&& pmouseX < width - margin 
&& pmouseY > margin
&& pmouseY < width - margin) {
      line(pmouseX,pmouseY,0, mouseX,mouseY, 0);
    }