I'm basically creating a display-module for an ad-system I've created.
I'm trying to avoid the following construction, with repeated if-statements.
My gut feeling tells me there's a smarter way to do this, maybe with polymorphism?
<?php
class Ad { 
    public $adState = 'active'; 
} 
class AdWriter { 
    public function displayAd(Ad $ad, $viewmode = 'visitor') { 
        if ($viewmode =='visitor') { 
            if ($adState == 'active') {} 
            else if ($adState == 'paused') {} 
            else if ($adState == 'inactive') {} 
        } 
        else if ($viewmode = 'owner') { 
            if ($adState == 'active') {} 
            else if ($adState == 'paused') {} 
            else if ($adState == 'inactive') {} 
        } 
        else if ($viewmode == 'administrator') { 
            if ($adState == 'active') {} 
            else if ($adState == 'paused') {} 
            else if ($adState == 'inactive') {} 
        } 
    } 
}  
?>
                There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge. Avoiding if-statements is not just about readability.
The experts in clean code advise not to use if/else since it's creating an unreadable code. They suggest rather using IF and not to wait till the end of a method without real need.
Apply the Refactoring Replace Conditional with Polymorphism and have a look at the State Pattern.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With