Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a more efficient 'if' statement for multiple options [closed]

I wonder if anyone has some ideas to make the following shorter and more efficient. I have 3 dropdowns where a user selects lower age limit, upper age limit and gender. They can select as many as they want, even none. I then have an if statement that will do a process based on what they select. Assume l, u and g are the parameters that are passed.

if((age > l && age < u && gender == g)
|| (age > l && age < u && g == null)
|| (age > l && u == null && g == null)
|| (age < u && gender == g && l == null)
|| (age < u ...etc etc)

Is there a better way of forming this rather then a tedious if statement?

like image 411
BMills Avatar asked Jan 21 '16 12:01

BMills


2 Answers

You can make it more readable by creating a variable for each condition.

var lowerAgeLimitMet = (l == null || age > l);
var upperAgeLimitMet = (u == null || age < u);
var genderLimitMet = (g == null || gender == g);
if(lowerAgeLimitMet && upperAgeLimitMet && genderLimitMet)
{
    //Do work here
}
like image 94
Synvert Avatar answered Nov 15 '22 16:11

Synvert


That should work:

if((age > l || l == null) && (age < u || u == null) && (gender == g || g == null))
   ...
like image 20
Fratyx Avatar answered Nov 15 '22 17:11

Fratyx