vendredi 11 décembre 2015

Return different objects based on conditional argument

I need help with some code desiging. I have a package which is used in many projects.

$p = new Package();
$result = $p->method();

While the Package looks like:

class Package {
    public function method($fooArg = 1, $barArg = 1)
    {
        // some logic

        return new SomeClass(
            $fizzArg,
            $buzzArg
        );
    }
}

Now, in one project which is using Package I need to change returned class. So, the call will look like this:

$p = new Package();
$result = $p->method(10, 10, true);

And the Package will look like this:

class Package {
    public function method($fooArg = 1, $barArg = 1, $condArg = false)
    {
        // some logic

        if (false === $condArg) {
            return new SomeClass(
                $fizzArg,
                $buzzArg
            );
        }

        return new MyNewClass(
            $fizzArg,
            $fooBarArg
        );
    }
}

Which design pattern should be used here? I do not want to return different object types based on condition, because it seems very ugly to me.

Aucun commentaire:

Enregistrer un commentaire