For a long time Robert Martin has been advising against if/else/switch branching logic and instead rely on the polymorphic behavior of different types. if/else/switch
should only be used in the factory creating the types with different behaviours. He describes the approach in a recent blog post. I feel I understand the thrust of his argument as applied in his example situation and I really like the concept as it pushes decision making to a single location, DRY & OCP.
However, I'm finding it difficult to apply the principle is some basic game dev situations.
e.g. consider this pseudo-code controlling a ball bouncing around a box (think 'Breakout')
void ball::update(){
if(collideswith(leftWall))
velocity.x= +speed;
else if(collideswith(rightWall))
velocity.x = -speed;
else if(collideswith(topWall))
velocity.y = -speed;
else if(collideswith(bottomWall))
velocity.x = +speed;
}
I am unsure what kind of polymorphic class I could build to replace the branching logic here.
Replacing the above code with an Uncle Bob solution might be over-engineering, but am interested in learning more about applying the principle in these kinds of contexts.
is_key_pressed
and whatever input handling logic. It would need a different approach. There could still be some generalization, such as key-callback pairs, I guess. \$\endgroup\$