Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make this repeating code look neater

EDIT: Forgot to mention that I’m on a constrained platform so I’m trying to use as little additional variables as possible.

...
switch (var->type) {
    case (something1):
        if (var->x >= 100 && var->x <= 105) {
            do_something(var);
            return;
        }
        break;

    case (something2):
        if (var->x >= 150 && var->x <= 155) {
            do_something(var);
            return;
        }
        break;

    case (something3):
        if (var->y >= 80 && var->y <= 85) {
            do_something(var);
            return;
        }
        break;

    case (something4):
        if (var->y >= 120 && var->y <= 125) {
            do_something(var);
            return;
        }
        break;
}
... 

Basically the code just checks the type of the variable, checks range on an axis specific to that type, and calls a function if the condition is met, does nothing if not. do_something() is the exact same function within all of the if segments.

I’m sure there’s an easy way to write this with less repetition, but I can’t seem to figure it out.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

How about:

switch (var->type) {
case (something1):
    if (! (var->x >= 100 && var->x <= 105)) return;
    break;
case (something2):
    if (! (var->x >= 150 && var->x <= 155)) return;
    break;
case (something3):
    if (! (var->y >= 80 && var->y <= 85)) return;
    break;
case (something4):
    if (! (var->y >= 120 && var->y <= 125)) return;
    break;
default:
    return;
}
do_something();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading