# If-statement consolidation

I often face the problem of stacked if-statements that look repetitive, but usually can't find an easy way to simplify it.

    if (keyState[BOTTOM]){
dig_direction = BOTTOM;
startDig(SIZE / 2 - x % SIZE, DIG_DEPTH);
} else if (keyState[RIGHT] && isTouching[RIGHT]){
dig_direction = RIGHT;
startDig(DIG_DEPTH, 0);
} else if (keyState[LEFT] && isTouching[LEFT]){
dig_direction = LEFT;
startDig(-DIG_DEPTH, 0);
}

-
Your code could probably be prettified, but not locally — there just isn't much material to work with here. We would need to take a look at the big picture. I encourage you to post a more comprehensive sample for review — probably as a separate question. –  200_success Aug 15 at 7:44

You want Replace Conditional with Polymorphism : "Move each leg of the conditional to an overriding method in a subclass. Make the original method abstract."

Your conditional from the example could then look like this :

digPosition.startDig()


digPosition being an instance of an interface DigPosition which has three implementations : BottomDigPosition, RightDigPosition and LeftDigPosition.

-
My bad! I'm using JavaScript not Java. –  John Aug 15 at 7:13
Ok, nevertheless, the pattern is applicable in javascript just as well I'd say. –  bowmore Aug 15 at 7:15
@bowmore I wouldn't be quite so sure about that. At least it's unproportionally more effort needed in JavaScript than in Java.... –  Vogel612 Aug 15 at 10:22
@Vogel612 well, I'm not familiar enough with javascript to judge that. But the amount of effort needed, does not invalidate the benefits of using the pattern. Of course we shouldn't blindly apply patterns, for the sake of having patterns. But if this same if structure (bottom/left/right) is repeated several times throughout the code, then the pattern is probably worthwhile. If it's just this one occurrence, then even in Java it would be overkill. –  bowmore Aug 15 at 12:15