Zug Zwang Zug Zwang - 2 months ago 9
PHP Question

Cascade of IF statements - best solution

I have this situation:

enter image description here

The User can choose between 3 products, A, B or C, like showed in the image. After the user clicks one of the products, he is redirected to a register form where he must include some data, including x and y. If the selected product and the value of x and y are not right, an error is launched. If the entered data is correct, then some other actions are done. I've tried to implement this control, but I'm not sure this is the best solution.

if ($product==("A") && x < 10 && y <= 2)
{
price = 10;

}

else if ($product ==("B") && x < 50 && y <= 10 && y >2)
{
price = 20;
}

else if ($product ==("C") && x < 250 && y <=50)
{
price = 30;
}

Answer

The "object oriented" approach here would be to avoid the "tell don't ask" pattern that you implemented.

Meaning: you are "asking" for certain properties; so that your code can make a decision based on that. The solution to that is: don't do it that way!

Instead: you create a "base" product class which offers methods like isXinRange() and isYinRange(). Then you have different sub classes for each product; and AProduct.isXinRange checks x < 10 ...

Meaning: your range checks go into three different classes!

And instead of putting everything into "one" comparison, you do something like:

  1. You create an object of AProduct for "A", BProduct for "B", ... and so on; like someProduct = generateProductFor(stringFromUser)
  2. Then you simply ask if someProduct.isXinRange() gives you true for the X provided by the user

(I am not too familiar with PHP, so sorry for my half-pseudo-half-java coding style here)