Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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);
    }
share|improve this question
2  
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

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.startDig()

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

share|improve this answer
    
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
2  
@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

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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