r/PHPhelp • • Jun 27 '18

Php Object Oriented Design. Need help

I have a list of operations and i need to calculate bank commission for every operation.

Operation types for now: cash in, cash out.
Person types can be: natural or legal. Not sure if there can be more types, but i thinking with in mind, that its possible.

Commission size depends on operation type and what person type made that operation:

Cash in commission for everyone, is 0.07% but not more than 4.00 Eur.
Cash out commission for legal person is 0.2% , but not less than 1.00 Eur.
Cash out commission for natural person is 0.2%, but person can cash out 1000 Eur in a week for free.

Input is csv file. With lines like this:
2015-12-31,1,natural,cash_out,1000.00,EUR
2016-01-05,2,legal,cash_in,200.00,EUR
2016-02-01,1,natural,cash_out,1000.00,EUR
(Second value is user id).

I want to do this using all good oop practices, solid principles etc. So far im doing it like this:

$calculator = new Calculator();

foreach ($data as $row) {

    $operation = OperationFactory::create($data); //Returns instance of class CashIn, class CashOut etc
    $calculator->addOperation($operation);

}

$results = $calculator->calculate();

And now it becomes very confusing to me. If tax price would only depend on operation type, i would do something like this:

class Calculator
{
    public function addOperation(Operations\Operation $operation)
    {

        $this->operations[] = $operation;

    }

    public function calculate()
    {

        foreach ($this->operations as $operation) {

            $result = $this->operation->amount * $operation->charge / 100;

            if ($result < $operation->min) {
                $result = $operation->min;
            } elseif ($result > $operation->max) {
                $result = $operation->max;
            }

            $results[] = $result;
        }

 return $result;
    }
}

I want to make this, that i could easily extend system with new operation types and new person types if neccesary. And this complicates the task for me. Escpecialy that part : "Cash out tax price for natural person is 0.2%, but person can cashout 1000 Eur in a week for free". In which place should i track all of this?

Im doing all this for learning purposes. Any help and tips appreciated.

8 Upvotes

11 comments sorted by

View all comments

Show parent comments

1

u/syob Jun 27 '18
class OperationFactory
{

    public static function create($row)
    {

        $data = explode(',', $row);

        $name = $data[3];

        switch ($name) {
            case 'cash_in':
                $operation = new CashInOperation();
                break;
            case 'cash_out':
                $operation = new CashOutOperation();
                break;
            default:
                break;
        }

        $operation->date = $data[0];
        $operation->person_id = $data[1];
        $operation->person_type = $data[2];
        $operation->name = $name;
        $operation->amount = $data[4];
        $operation->currency = $data[5];
        $operation->person= PersonFactory::create($operation->person_id, $operation->person_type);

        return $operation;
    }
}

2

u/cryptichorizon77 Jun 27 '18 edited Jun 27 '18

To be able to calculate "person can cashout 1000 Eur in a week for free", your code needs to know how much each person cashed out so far, for at least one week. So that information is in the csv data, but you need an accumulation of it for the current week so far.

I can't see in your current model that you store the data anywhere. So either each csv file always represents one whole week's worth of data, or you will need to write something that stores the data (in a db perhaps) as it imports it. You can then uses that "historical" data to re-calculate the current weekly cach-out total for each person when you process a new csv file.

Make sense?

1

u/syob Jun 27 '18

Normally i would imagine how to calculate that part, but i cant understand where should i put this calculation in overall structure and even how this structure should look like.

I was following this open closed principle example https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design#open-closed-principle .

Now if i want to create a new type of operation, e.g. named transaction. I would make new class Transaction (which extends Operation) with property $charge and set some value to it. Then my calculator class could calculate that. This part i understand.

But now how i need to design this further?When my Transaction charge depends on which person(legal or natural) made that operation.

3

u/cryptichorizon77 Jun 27 '18 edited Jun 27 '18

Well, for a start you could take the code that does the calculation out of your Calculation class, create a new set of classes for each type of person and put code to do the actual calculation for each type in a common method. So something like:

interface PersonType
{
    public function calculate($operation);
}

class LegalPerson implements PersonType
{
    public function calculate($operation)
    {

        $result = $this->operation->amount * $operation->charge / 100;

        if ($result < $operation->min) {
          ....
        }


        return $result;
    }
}

class NaturalPerson implements PersonType
{
    public function calculate($operation)
    {       
        ....
    }
}

Now, in the loop in your Calculate class you can delegate to the PersonType object to do the calculation:

public function calculate()
{
    foreach ($this->operations as $operation) { 
        $results[] = $operation->person->type->calculate(); 
    }
    return $results; 
}

Of course, my examples don't shown how $operation->person->type actually gets a value, but see if you can figure that out.

1

u/syob Jun 28 '18

Sorry, still dont get it. Is it mistake or i dont understand this $operation->person->type->calculate()? I image it was suppose to be just $operation->person->calculate()?

Posible i dont understand what you meant at all. But if it was a mistake, then this is how i understand further. So each person type will have its own class, which calculates. But then i need to check what type of operation person is calculating. Because for natural person cash out charge fee is 0.2% but for another could be different.

So i would do this:

class NaturalPerson implements PersonType
{
    public function calculate($operation)
    {
        switch ($operation->name) {
            case 'cash_in':
                //calculate cash in commission for natural person...
                break;
            case 'cash_out':
                //calculate cash out commission for natural person...
                break;

            default:
                break;
        }
    }
}

In this case, when new operation type would be introduced, i would need to add new case to every person class. Which i think is not the best way ?

2

u/cryptichorizon77 Jun 28 '18

Your approach of making $operation->person contain the PersonType classed should work fine. I was thinking of doing it a bit differently, but nothing wrong with your way.

Now with regard to the switch ($operation->name) statement. Sure, it's probably not ideal. Sure, it probably breaks with the Open Closed Principles. Sure, there are probably a number of clever ways to get rid of it and make it more elegant and more OO.

But, before you try to do that I am going to ask you to consider if that is really necessary?

You currently have 2 person types and 2 operation types. How often do you expect new ones to come up? Is having to add a another case in your switch statement really that much work? Sure, it might become too much work one day when you have 5 person types and 7 operation types and then it might make sense to refactor the code to something more manageable. But does it make sense to worry about it now? What if you never end up never having to any new operation or person types? You cannot predict the future, so you cannot make your code cater for every little thing that might change one day.

Be careful of Premature Optimisation. It's easy to get stuck in a Optimisation Rabbit Hole, which can easily become an Optimisation Death Spiral. There is always going to be bits of code that is not Open or Closed enough, too Coupled and not Cohesive enough, has more than one Responsibilities etc. etc. The trick is realising when good enough is good enough and moving on, so you don't get stuck.

It's perfectly possible to follow the SOLID Principles religiously and actually make your code more complex rather than less. These are Principles, not Laws. They need to be traded off against each other and against other concerns.

All of that said, if you really want to get rid the switch statement, I might do another post with some ideas later when I have some time. Maybe somebody else has suggestions...

2

u/syob Jun 28 '18

You are right, probably there never be another person type. And to add one more case for each Person class if new Operation type comes up is not too much work at all. And its logical too me, i wanted to not break open closed principle just for sake of it. So its really not necessary now indeed. But if you have time to post how you get rid that switch statement, it would be interesting for me to see.

I will try now to finish this task that way how i understand at this moment. You helped me a lot, thanks!

2

u/cryptichorizon77 Jun 30 '18 edited Jun 30 '18

A common object oriented alternative to long switch or if..else statements is to use some kind of Lookup mechanism.

This gets rid of your switch statement, but it also makes the whole thing we did with the PersonType interface and *Person classes kinda pointless. So lets pretend that the last few comments didn't happen and your code is back to the way it was at the beginning of the thread.

First let's define a new interface for the classes that will calculate our commission from operations:

interface CommissionCalculator {
    public function calculate($operation);
}

Notice that what we are doing here is keeping the concept of "thing that calculates commissions" decoupled from both the concepts of "type of person" and "type of operation". We will create implementing classes that actually does the calculation for specific cases.

If we go back and look at the specs in your OP, it seems that cash-in calculations are going to be pretty similar regardless of whether it's for a natural or legal person, so let's create a single class for that:

class CheckInCommCalculator implements CommissionCalculator {
    public function calculate($operation) {
        ...
    }
}

Next, lets just assume that the cash-out calculations for the different person types are different enough to warrant a separate calculation class for each:

class NaturalPersonCashOutCommCalculator implements CommissionCalculator {
    ...
}

class LegalPersonCashOutCommCalculator implements CommissionCalculator {
    ...
}

Let's go back to your main Calculator class for the rest of the steps. (You'd probably want to actually put the Lookup table mechanism in it's own class, but for simplicity, let's not do that now)

Create instances of each of our commission calculators (you can do this in your constructor or another method):

$cashInCalculator = new CashInCommCalculator();
$naturalCashOutCommCalculator = new NaturalPersonCashOutCommCalculator();
$legalCashOutCommCalculator = new LegalPersonCashOutCommCalculator();

We can now set up a lookup table using arrays:

$this->lookupTable = [
    ['cash_in', 'natural', $cashInCalculator],
    ['cash_out', 'natural', $naturalCashOutCommCalculator],
    ['cash_in', 'legal', $cashInCalculator],
    ['cash_out', 'legal', $legalCashOutCommCalculator]
];

... and write a method that scans lookup the table and returns the specific CommisionCalculator we set up for a given operation and person type combination (I'll leave the implementation up to you):

private function lookupCommissionCalculator($operation) : CommissionCalculator 
{
    $operationType = $operation->name, 
    $personType = $operation->person_type
   ...
    return $commisionCalculator
}

Finally we can rewrite the original calculation method in your Calculator class to look something like this:

public function calculate()
{
    foreach ($this->operations as $operation) {
        $commissionCalculator = $this->lookupCommissionCalculator($operation);
        $result = $commissionCalculator->calculate($operation);
        $results[] = $result;
    }
    return $results;
}

And there you have it.

Now your Calculator calculate method doesn't have to know anything about person types or operation types or whatever other details are added in the future. To add a new types of calculation, you don't have to change the function at all, all you need to do is add new entries to the lookup table containing instances of existing or new *CommissionCalculator classes. Which means that method is now more closed to modification, while still being open to extension.

But... Is this better than just having a switch statement with four cases? Is it simpler or more complex? Is it more or less elegant? More work or less work? Is the extra work worth it, right now. Would it have been worth it, in the future, even if the types of changes your design anticipated never happened?