Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce code duplication in this example

I need to loop through a number (xx). xx always starts at zero. My problem is that if the moveDirection variable is +1 then xx increases until it reaches the positive of range. If moveDirection is -1, then xx decreases until reaching the negative of range.

In the code below, I have done this by having an if statement test for moveDirection first, then I have duplicated the for loop, and edited the values for each case. My code happens to be in ActionScript3, but the language does not matter.

var p:Point;
var xx:int;

if (moveDirection > 0)
{
    for (xx = 0; xx < range; xx++)
    {
        if (hitTestPoint(xx, yy))
        {
            return true;
        }
    }
}
else 
{
    for (xx = 0; xx > range; xx--)
    {
        if (hitTestPoint(xx, yy))
        {
            return true;
        }
    }
}

Is there a better way of doing this, maybe without duplicating the for loop? If there is any other advice, it would be greatly appreciated.

like image 469
Adam Harte Avatar asked Dec 16 '22 23:12

Adam Harte


2 Answers

for (xx = 0; xx != range; xx += moveDirection)
{
    if (hitTestPoint(xx, yy))
    {
        return true;
    }
}

This assumes that moveDirection will be either 1 or -1 for going up or down, respectively. Also, you'll have to slightly change your range for the != to work properly. But, it does cut down on code.

like image 142
fire.eagle Avatar answered Jan 22 '23 21:01

fire.eagle


From the looks of the code, it doesn't really matter which direction the loop runs -- you're just returning true if hitTestPoint returns true for some value in the range. If that's so, another possibility would be something like:

var start:int = min(0, range);
var stop:int = max(0, range);

for (xx = start; xx!=stop; xx++)
    if (hitTestPoint(xx,yy)
        return true;
like image 30
Jerry Coffin Avatar answered Jan 22 '23 19:01

Jerry Coffin