patternjavascriptMinor
If-statement consolidation
Viewed 0 times
consolidationstatementstackoverflow
Problem
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);
}Solution
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
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.Code Snippets
digPosition.startDig()Context
StackExchange Code Review Q#60112, answer score: 3
Revisions (0)
No revisions yet.