BatWannaBe
BatWannaBe

Reputation: 4510

More strategies for refactoring long conditional statements

Fair warning, I'm a self-taught Python amateur, but I don't expect Python-only solutions and want to hear good strategies from any language. Just try to dumb it down for me.

I've seen 2 main suggestions for fixing the infamously long if-else statements in the code of the game Yandere Simulator (if you know, you know):

  1. enum & switch: Simple if-else comparisons can be changed to constant flags labeled by an enum. A switch statement checks sorted constant values more efficiently than a sequential if-else chain.
  2. class polymorphism: Instead of 1 method with a giant if-else chain checking an object for what is essentially its class, make classes with their own methods.

I'm not entirely satisfied with these suggestions for the following reasons:

  1. A) Just changing a possibly nested if-else to a switch statement can make it slightly more readable, but it's still a long conditional, possibly longer.

    B) Calculating and storing every condition as a flag somewhere may not be feasible or readable, like a condition that is a combination of field values

  2. Though polymorphism can actually structure the code, not every condition should be a class. For example, professions like Teacher and Student are reasonable classes, maybe subclasses of Person. However, a Person's eye color and height should be fields, not their own classes.

So, assuming I've done all these suggestions as much as possible and am still stuck with long conditional statements checking combinations of field values, what else can be done without changing the code's behavior?

Upvotes: 0

Views: 220

Answers (1)

Peter R
Peter R

Reputation: 364

I do not know the code, but if it is impossible to fix, there could be a bigger problem with the design. So basically moving up one level to see if the architecture of that piece should be reviewed altogether. Sounds like more than one problem you have to fix.

What helped me was reading up on Martin Fowlers book on refactoring, He really goes deep into this subject.

Upvotes: 1

Related Questions