DEV Community

Discussion on: Static classes are evil

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

I think the article is quite correct. But there is a critical unstated assumption: that static classes operate on a shared mutable state. The correct use of static methods are as deterministic functions. For example String.Join(",", strings) is probably deterministic in a given language, making it easily testable and understandable.

Collapse
 
wrongabouteverything profile image
wrong-about-everything

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.

Collapse
 
kspeakman profile image
Kasey Speakman

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!