

Static Classes Are Evil, Make Your Dependencies Explicit
source link: https://www.tuicool.com/articles/hit/R3uAJzF
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Static Classes Are Evil, Make Your Dependencies Explicit
DZone's Guide to
Static Classes Are Evil, Make Your Dependencies Explicit
According to one developer, static classes are evil. Click here to learn more about one dev's approach to static classes and keeping dependencies explicit.
Free Resource
Join the DZone community and get the full member experience.
Verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!
In spite of some languages, e.g. PHP or Java, some languages don’t have (top-level) static classes. However, the concept is still present. A class consisting entirely of static methods is effectively the same thing as a static class.
Besides, static classes are procedural , and their clients are untestable — well, there are some hacks in Java and PHP, but I don’t want to mention them. Because they have even more issues.
Classes Tend to Go From 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 an imperative and non-OOP process.
Dependencies Are Hidden
Code is also less readable. What’s in the class? Database queries, some intense calculations, email sending? You just don’t control how many of them are in one 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 for a large number of dependencies is that they are at lower abstraction levels. 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 a static method, you need to make sure that none of the other clients get broken. So, such reuse simply doesn’t work. I can compare it with my noble (and failed) attempt to compose and reuse microservices . 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 a client’s financial balance from my posts about Super PSP architecture . It has all mentioned drawbacks and looks like this:
class FinancialBalanceUtils { static public void reserveBalance() { if (!shouldReserve()) { return; } assertAllConditionsAreMet(); queryFinancialBalanceForCurrentClient(); boolean result = checkFinancialBalance(); if (!result) { return false; } 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 through the 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 with the assertAllConditionsAreMet()
method.
Then, we get financial balance by tons of parameters from a database with the queryFinancialBalanceForCurrentClient() method
, as the query and database table serve the needs of every client who needs financial balance. However, we are still not sure if the financial balance is fine. We need to check what’s in there using the method checkFinancialBalance()
.
Now, finally, we 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, therefore, consists of hidden dependencies. How much database queries are executed in this method? I don’t know.
Try OOP, Instead
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 difficult to edit? Let's try OOP, instead.
- Identify your objects . 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 like too much already. When there are more than five, 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 . Implement only some specific scenarios first.
Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.
Recommend
-
7
How to ask questions of your interviewer without seeming evil I've noticed a common theme in discussions of my "put down the crack pipes" post. Specifically, when it c...
-
12
Make your Ruby code more modular and functional with polymorphic aggregate classesHi, weʼre arkency 👋 For the last year, I’ve been using Rails (as I do for the last 10 y...
-
5
Singleton vs. static classes in C# Understand the differences between a singleton class and a static class and when to use which in your applications. When developing applications in .NET Core, you might often ne...
-
5
How to Make Your Classes Compatible with Range for Loop Published September 2, 2021 - 0 Comments Today...
-
9
When practicing software architecture and design, one important consideration is how the rules of the system are modeled. Are the rules ad hoc and a matter of tribal knowledge of the developers who came before, or are they explici...
-
7
Do Java classes have a machine level instance (JVM) if they contain only static methods and fields? advertisements Do Java...
-
4
Hidden Dependencies Are Evil - Arguing With The Clean Code (Slightly) February 19, 2011 Hidden dependencies are evil because tw...
-
5
Buying Frenzy You are building a backend service and a database for a food delivery platform, with the following 2 raw datasets: Restaurants data Link:
-
8
BlogHow to make your web application more secure by using Static Application Security Testing (PART 1 of 5 in Application Security Testing series)
-
7
Mockito 5 Supports Mocking Constructors, Static Methods and Final Classes out of the Box Jan 30, 2023...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK