Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you avoid static classes? [closed]

Tags:

Are static classes considered bad practice? I read an article about this a couple days ago (can't find it, sorry) which basically said that having static classes (especially those 'helper' classes) are typically a sign of bad code. Is this correct, and if so, for what reasons?

like image 467
Alex Avatar asked Aug 22 '09 03:08

Alex


People also ask

Why You Should Avoid static classes?

Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.

Should you avoid static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages.

Are static classes better?

Static classes and static members are useful because they do not require instances created for each new object. That means, they consume fewer resources and no duplication of the same class or member is needed in memory. Static members make code cleaner.


2 Answers

The abuse of static classes can be considered bad practice. But so can the abuse of any language feature.

I make no distinction between a non-static class with only static methods and a static class. They are effectively the same thing, except that static classes allow the compiler to enforce the developers intent (no instantiating this class, convenient syntax for accessing its functionality, etc).

As you say, a proliferation of "Helper" classes can get you into trouble (design, maintainability, readability, discoverability, other-abilities...). No argument here. But can you argue that a "Helper" class is never appropriate? I doubt it.

Indeed, responsible use of static classes can have great benefits to your code:

  • The Enumerable static class provides a set of extension methods most of us have come to love. They are a logical set of functionality / business logic that isn't related a instance of any particular type.
  • Services provided by the environment/context: eg Logging, Configuration (sometimes)
  • Others (that I can't think of at the moment :))

So no, in general its not bad practice. Just use them wisely...

like image 162
Nader Shirazie Avatar answered Oct 01 '22 06:10

Nader Shirazie


I think the general argument is against keeping mutable state in static classes, and basically using them as global variables. There's nothing wrong with static helper methods in a static class.

And as to why global variables are bad, I'm sure between here and google you'll find half a millions pages and blog posts about it.

like image 24
Davy8 Avatar answered Oct 01 '22 05:10

Davy8