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 case
check or an if/elseif
chain 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.
Are you saying you have a different class for each permission level (something like AdminOrder
, SalesmanOrder
, etc)? If so, it is better add a separate method in each class if the order is sufficiently different. Doing this is called method overriding, and is common in object-oriented programming. Take for instance:
class Order
{
function start_order()
{
// this method contains common code for all orders
}
}
class AdminOrder extends Order
{
function start_order()
{
// IF NEEDED: call start_order on Order. This is if you have common code that should be executed for ALL subclasses of Order
parent::start_order()
// Now implement code specific to an AdminOrder
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With