Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid big switch statements?

I have an internal application in which one function is containing too many switch cases.

This is developed in php.This specific function is used to write changes to database and also to keep a history of individual field values. So what it does is have a case for each field as different things needs to be applied for different fields.

switch ($item){  
    case 'item1':  
        do_something();  
    case 'item2':  
        do_something_different():  
}

Is there a design pattern to follow in such cases. A function for each item doesn't look so future proof either.

Update: pastebin link

like image 455
0xdeadbeef Avatar asked Dec 12 '22 20:12

0xdeadbeef


1 Answers

That's just not a good function. It should be three functions, edit_name, edit_manager and edit_liscencedata. you can move all the stuff that repeats between cases into the constructor of the Change class that you should define.

like image 57
aaronasterling Avatar answered Dec 27 '22 03:12

aaronasterling