Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding if-statements with object oriented design, PHP

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') {} 
        } 
    } 
}  

?>
like image 306
Poyan Avatar asked Jun 16 '11 11:06

Poyan


People also ask

Should you avoid using if statements?

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.

Why should we avoid if-else?

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.


1 Answers

Apply the Refactoring Replace Conditional with Polymorphism and have a look at the State Pattern.

like image 117
Gordon Avatar answered Sep 23 '22 22:09

Gordon