i am using codeigniter.
i have class Orders which with some methods like start_order(), close_order(), etc..
and i have a permission level for each user type 'admin','salesman','manager' ..
therefore the same method may get different implementation each time.
so, my question is: which is considered as best practice in CI :
1) to make a big method in the ‘orders’ class that contains the
different logic details. or
2) repeat the method as needed in
other classes.
i know it sounds obvious that one should go for the first choice. but, when i did that i ended up with massive blocks of code. so, this is why i am asking for your experience.
As a matter of fact it is not obvious that one should go for the first choice (“one big method”). That should definitely be avoided.
In general, one should prefer small methods. Each method should do exactly one thing and only one thing, have only one reason to ever change, be small and readable, be obvious from its name what it is doing, etc.
The wording you choose in your question (“different implementation each time” and “that contains the different logic details”) implies that you’re talking about one method which does different things based on some kind of state of the objects.
Take a look at a refactoring pattern called Replace Conditional With Polymorphism. This pattern is commonly used when you have a method which is primarily a big
casecheck or anif/elseifchain which determines that state. The idea is that you’d extract each implementation into its own class which overrides a method on a base class. The classes would hold and know about the state and would be able to apply the correct logic accordingly, and the consuming code would just call the method on the base class type.There is lots of information and lots of examples on this pattern.
As @Gordon points out, this is also called the Strategy Pattern.