Should conditional expressions go inside or outside of classes?

Posted by Rupert on Stack Overflow See other posts from Stack Overflow or by Rupert
Published on 2010-05-22T22:49:39Z Indexed on 2010/05/22 23:00 UTC
Read the original article Hit count: 231

Filed under:
|
|

It seems that often I will want to execute some methods from a Class when I call it and choosing which function will depend on some condition. This leads me to write classes like in Case 1 because it allows me to rapidly include their functionality. The alternative would be Case 2 which can take a lot of time if there is a lot of code and also means more code being written twice when I drop the Class into different pages.

Having said that, Case 1 feels very wrong for some reason that I can't quite put my finger on. I haven't really seen any classes written like this, I suppose.

Is there anything wrong with writing classes like in Case 1 or is Case 2 superior? Or is there a better way? What the advantages and disadvantages of each?

Case 1

class Foo {
    public function __construct($bar) {
        if($bar = 'action1') $this->method1();
        else if($bar = 'action2') $this->method2();
        else $this->method1();
        }

    public function method1() { }
    public function method2() { }
    }

$bar = 'action1'
$foo = new Foo($bar);

Case 2

class Foo {
    public function __construct() { }
    public function method1() { }
    public function method2() { }
    }

$foo = new Foo;
$bar = 'action1';
if($bar == 'action1') $foo->method1();
else if($bar == 'action2') $foo->method2();
else $foo->method1();

© Stack Overflow or respective owner

Related posts about php

Related posts about classes