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);
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Commented Aug 15, 2014 at 7:44

1 Answer 1


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 being an instance of an interface DigPosition which has three implementations : BottomDigPosition, RightDigPosition and LeftDigPosition.

  • \$\begingroup\$ My bad! I'm using JavaScript not Java. \$\endgroup\$
    – John
    Commented Aug 15, 2014 at 7:13
  • \$\begingroup\$ Ok, nevertheless, the pattern is applicable in javascript just as well I'd say. \$\endgroup\$
    – bowmore
    Commented Aug 15, 2014 at 7:15
  • \$\begingroup\$ @bowmore I wouldn't be quite so sure about that. At least it's unproportionally more effort needed in JavaScript than in Java.... \$\endgroup\$
    – Vogel612
    Commented Aug 15, 2014 at 10:22
  • 2
    \$\begingroup\$ @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. \$\endgroup\$
    – bowmore
    Commented Aug 15, 2014 at 12:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.