Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is better practice big one method or separated methods?

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.

like image 908
adel Avatar asked Dec 21 '22 22:12

adel


2 Answers

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.

like image 156
David Avatar answered Dec 23 '22 11:12

David


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
    }
}
like image 31
Logan Serman Avatar answered Dec 23 '22 11:12

Logan Serman