mardi 20 septembre 2022

Best Practice for OOP function with multiple possible control flows

In my project, I have this special function that does needs to evaluate the following:

  1. State -- represented by an enum -- and there are about 6 different states
  2. Left Argument
  3. Right Argument

Left and Right arguments are represented by strings, but their values can be the following:

  1. "_" (a wildcard)
  2. "1" (an integer string)
  3. "abc" (a normal string)

So as you can see, to cover all every single possibility, there's about 2 * 3 * 6 = 36 different logics to evaluate and of course, using if-else in one giant function will not be feasible at all. I have encapsulated the above 3 input into an object that I'll pass to my function.

How would one try to use OOP to solve this. Would it make sense to have 6 different subclasses of the main State class with an evaluate() method, and then in their respective methods, I have if else statements to check:

  • if left & right arg are wildcards, do something
  • if left is number, right is string, do something else
  • Repeat for all the valid combinations in each State subclass

This feels like the right direction, but it also feels like theres alot of duplicate logic (for example check if both args are wildcards, or both strings etc.) for all 6 subclasses. Then my thought is to abstract it abit more and make another subclass:

For each state subclass, I have stateWithTwoWildCards, statewithTwoString etc.

But I feel like this is going way overboard and over-engineering and being "too" specific (I get that this technically adheres tightly to SOLID, especially SRP and OCP concepts). Any thoughts on this?

Aucun commentaire:

Enregistrer un commentaire