r/PHPhelp • u/NewCoding • Jun 01 '17
Writing a large algorithm, is there a better way than using a hundred switch statements? Is this bad practice or the only way to do it?
I'm writing an algorithm for an MMO gear optimization site that has to take a lot of things into account. I am wondering if using a bunch of switch statements is considered bad practice, or if it's the only way to get the job done.
An example is the user will input each item equipped in each gear slot, what their gameplay goals are, etc. and I will then process that to show if their next goal should be a gear upgrade (and which of the 10 slots would be most beneficial based on the items stats), or if they should focus on increasing their energy, or if they should focus on doing one of the 5 other things available (of which some would be broken down into even more switch statements depending on their current progression).
I can provide a more detailed breakdown when I get home, I'm stuck in a traffic jam on mobile right now so I figured I may as well post this to see if this would be enough information to get an answer.
Thanks!
1
u/wh33t Jun 01 '17
I don't believe Switch carries anymore overhead than than if/else. I think you'll just want to focus on writing clean and efficient logic that reduces that number of checks.
Cool project!
3
u/NewCoding Jun 01 '17
Alright, thanks! If anything I was assuming switch would possibly carry less overhead since a bunch of checks can be maintained in a single switch as opposed to (inevitably) writing a ton of if/else checks for every condition.
1
u/wh33t Jun 02 '17
You can write switch like
switch($somevar) { case somecase: case someothercase: //do something break; }and I'm pretty sure that's exactly the same as
if($somevar == somecase || $somevar == someothercase) { //do something }So I think it just comes down what is easier to read/write subjectively. I use switch as often as I can.
1
u/skintagain Jun 06 '17
Have a look at the Decorator pattern - some examples here. Decent class design will significantly reduce the switch requirement.
1
u/phtip Jun 11 '17
Can you use tables?
| Thing | Level | Points | Requirement | Help | ... |
|---|---|---|---|---|---|
| Item X | 2 | 20 | HP | Find a red... | ... |
Then the logic can be in a small loop that checks the requirements from your tables.
1
u/Raydr Jun 01 '17
I would recommend you try flowcharting it out. Based on this, you'll have a better visual to assist in selecting a pattern or architecture.