Home > Enterprise >  How can i avoid conditional statements or/and switch statements?
How can i avoid conditional statements or/and switch statements?

Time:06-09

This is my requirement from a recruiter:

Please avoid usage of conditional statements or/and switch statements to different product types in runtime

This is the code I wrote:

<?php
    if ($product['product_type'] === "DVD") {
        echo "<p>Size: ".$product['size']."MB</p>";
    } elseif ($product['product_type'] === "Furniture") {
        echo "<p>Dimentions: ".$product['dimentions']."</p>";
    } elseif ($product['product_type'] === "Book") {
        echo "<p>Weight: ".$product['weight']."Kg</p>";
    }
?>

How can I avoid this logic with some of the OOP concept?

CodePudding user response:

To avoid using conditionals you could use some sort of lookup to match the type to the field display I think.

Something like this perhaps:

$lookup = [
  "DVD" => ["field" => "size", "append" => "MB"],
  "Furniture" => ["field" => "dimentions", "append" => ""],
  "Book" => ["field" => "weight", "append" => "Kg"],
];

$LookupItem = $lookup[$product["product_type"]];
echo $product[$LookupItem["field"]].$LookupItem["append"];

Live demo: https://3v4l.org/Kc4hV

  • Related