loading...

re: Static classes are evil VIEW POST

TOP OF THREAD FULL DISCUSSION
re: I think the article is quite correct. But there is a critical unstated assumption: that static classes operate on a shared mutable state. The corre...
 

there is a critical unstated assumption: that static classes operate on a shared mutable state

There's no such assumption. Every issue I've listed holds true without it. And concerning your example, here is how I would write it:


interface String
{
    public function value();
}

class DefaultString implements String
{
    private $string;

    public function __construct($string)
    {
        $this->string = $string;
    }

    public function value()
    {
        return $this->string;
    }
}

class Joined implements String
{
    /**
     * @var String[]
     */
    private $strings;
    private $delimeter;

    public function __construct(array $strings, $delimeter)
    {
        $this->strings = $strings;
        $this->delimeter = $delimeter;
    }

    public function value()
    {
        return
            implode(
                $this->delimeter,
                array_map(
                    function (String $s) {
                        return $s->value();
                    },
                    $this->strings
                )
            );
    }
}

class UpperCase implements String
{
    private $string;

    public function __construct(String $string)
    {
        $this->string = $string;
    }

    public function value()
    {
        return strtoupper($this->string->value());
    }
}

var_dump(
    (new Joined(
        [
            new UpperCase(new DefaultString('harry')),
            new UpperCase(new DefaultString('potter')),
        ],
        ' '
    ))
        ->value()
);

It looks way more declarative, human-readable, composable and reusable.

 

There's no such assumption. Every issue I've listed holds true without it.

Eh, not really. I mean I get it... statics are incompatible with OOP or "objects all the way down" philosophy. Right on. But they have valid uses which remain testable and maintainable, albeit not following the OOP philosophy.

Anyway, not meant to argue your main point. I think you are right. Just that there are nuances to every tool. Best wishes!

Code of Conduct Report abuse