Static classes are evil
Tags: oop, solid, programming
Published: 2017-12-20 10:48:18

---
title: Static classes are evil
published: true
description: ... or are they?
tags: oop, solid, programming
canonical_url: https://medium.com/@wrong.about/static-classes-are-evil-or-make-your-dependencies-explicit-af3e73bd29dd
---
In spite of some languages, e.g., PHP, don’t have such thing as static classes, the concept is still present there. Class consisting entirely of static methods is effectively the same thing as static class.

Besides static classes are [procedural](http://www.yegor256.com/2015/02/20/utility-classes-vs-functional-programming.html) and their clients are [untestable](http://michalorman.com/2012/04/stop-writing-static-methods/) (well, there are some hacks in Java and PHP, but I don’t even want to mention them), they have couple of more issues.

##Classes tend to be big to huge
Since classes with static methods have nothing to do with objects, they don’t know who they are, what they should do and what they should not do. The boundaries are blurred, so we just write one instruction after another. It’s hard to stop until we’re done with our task. It is inevitably imperative and non-OOP process.

##Dependencies are hidden
Code is way less readable. What’s in the class? Database query, some intense calculations, email sending? You just don’t control how many of them are in the class. One static method here, one there — and here it is, our new God object. And when you realize that, it’s already too late.

##Low cohesion
Hence the class is getting less and less cohesive. If the class has a lot of dependencies, chances are that it does more than it should. For the sake of justice I should say that the possible reason of large number of dependencies is that they are at lower abstraction levels. So composing dependencies in higher-level abstractions could be the way to go.

##Tight coupling
Static methods mean that they can be called from anywhere. They can be called from a lot of contexts. They have a lot of clients. So if one class needs some little special behavior to be implemented in static method, you need to make sure that none of the other clients got broken. So such reuse simply doesn’t work. I can compare it with noble (and failed) attempt to compose and [reuse microservices](https://medium.com/@wrong.about/wrong-ways-of-defining-service-boundaries-d9e313007bcc). The resulting classes are too generic and completely unmaintainable. This results in the whole system being tightly coupled.

##Example
As an example let’s consider client’s financial balance (taken from [Payment Service Provider example](https://medium.com/@wrong.about/example-of-service-boundaries-identification-e9077c513560)). It has all mentioned drawbacks and looks like this:
```php
class FinancialBalanceUtils
{
    static public function reserveBalance()
    {
        if (!self::shouldReserve()) {
            return;
        }
        self::assertAllConditionsAreMet();
        self::queryFinancialBalanceForCurrentClient();
        $result = self::checkFinancialBalance();
        if (!$result) {
            return false;
        }
        self::reserveFinancialBalanceForCurrentClient();
    }
}
```

So, let’s inspect it from the beginning.

We are not sure where it is called from as it can be called from absolutely anywhere. So we need to make sure that this method really should be executed, hence _shouldReserve()_ method.
We are not sure where it is called from, once again! Are all preconditions satisfied? No one knows, so we absolutely must verify this —_assertAllConditionsAreMet()_ method.
Then we get financial balance by tons of parameters from database with _queryFinancialBalanceForCurrentClient()_ method, as the query and database table serve the needs of every client who needs financial balance.
OK, we are still not sure if the financial balance we got is fine. We need to check what’s in there — _checkFinancialBalance()_.
Aaand finally we really do reserve the balance with _reserveFinancialBalanceForCurrentClient()_.

I omitted logging, error handling and minor code quirks and kept only the essentials. And it’s already too big.
This class is a hidden dependency itself, and it consists of hidden dependencies. How much database queries are executed in this method? I don’t know.
Do you still have any doubts that this class does more than it should?
Was it worth it to allegedly avoid copy-paste which resulted in completely unmaintainable, super-generic code that is really scary to edit?

##Try OOP instead

* [Identify your objects](https://medium.com/@wrong.about/how-to-avoid-anemic-domain-model-5e1c3e6fe4d0). Focus on “what”, not “how”. Focus on objects, not procedures.
* When objects are identified, make all your dependencies explicit first, and limit their number. Limit it to five per method. Why five? I don’t know, it just sounds reasonable. Six feels too much already. When there are more than five probably your class wants to do more than it should. Or, probably, the abstraction level of those dependencies is too low. Anyway, explicit dependencies give you a chance to make your design more solid.
* Don’t generalize too early, remember [the Rule of Three](https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)). First implement only some specific scenarios.

---
Here is a cross-posted version from my [medium post](https://medium.com/@wrong.about/static-classes-are-evil-or-make-your-dependencies-explicit-af3e73bd29dd).