Edit:
I should have mentioned that I wanted it to be more Object Oriented. And I don't think my code here is anywhere near OO and neither is using switches, is it?
OP:
First of all, in my below example I am working with dutch units, so the calculations might seem off, but you'll get the idea.
Basically, what I have is a grocery list with products. In my database I store prices in "price by piece" or "price by pound", for example. So in order for calculating the total price of each product, based on the amount selected, I am working with the below class.
Example:
In my grocerylist I have a few products, and behind that product is a text field and a dropdown. In the textfield I can enter the amount I want to have, and in the dropdown I select if it needs to be ounces, pounds, and so on. Based upon those values, and the initial price from my database (price per piece and so on), I can calculate the total price for each product.
class Calculation
{
protected $price;
protected $amount;
protected $unit;
public function __construct($price, $amount, $unit)
{
$this->price = $price;
$this->amount = $amount;
$this->unit = $unit;
}
public function calculate()
{
if($this->unit === 'ounce')
{
return $this->formatOunce();
}
if($this->unit === 'pound')
{
return $this->formatPound();
}
return $this->formatOne();
}
public function formatOne()
{
return $this->price * $this->amount / 100;
}
public function formatOunce()
{
return $this->price / 1000 * $this->amount / 100;
}
public function formatPound()
{
return $this->price / 1000 * 500 * $this->amount / 100;
}
}
The problem I have is this:
public function calculate()
{
if($this->unit === 'ounce')
{
return $this->formatOunce();
}
if($this->unit === 'pound')
{
return $this->formatPound();
}
return $this->formatOne();
}
How would I change the above code in order for it to be good OO? Do I use a Repository or an Interface for that? Or can I do that within this particular class to keep it simple? I feel there is way too many IF's.