1

Firstly, I would like to briefly define a state to make sure we're on the same page. (please correct me if I'm wrong, or if you have anything to add)

  • Mutable variables/objects in the class.
  • Likely to be used in other classes, therefore creating a reference.

I've heard the main use of static in classes is for utility classes, which basically just provide global access to common methods -- and when states need to be stored, you should use a Singleton. However, I do not understand exactly why states are BAD for static classes? (Please correct me if this ideology is wrong)

Riley Ngi
  • 41
  • 1
  • 2
    See [this](https://softwareengineering.stackexchange.com/questions/148108/why-is-global-state-so-evil) – Sweeper Dec 05 '20 at 06:22
  • 3
    Note on terminology (or as I understand the terminology): "Static classes" are [nested classes](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html) which are declared `static` and they function just like a top-level class; this is different from "utility classes" which are classes that only have static methods (and typically a private constructor to prevent instantiation). – Slaw Dec 05 '20 at 06:29
  • 1
    Actually, singletons share most of the problems of global variables and should also be avoided if possible. They make it harder to predict what the state of your program is at any given point, and they make it easy to create hidden dependencies between unrelated parts of the code. – Hulk Dec 05 '20 at 06:30
  • To support @Hulk comment: https://stackoverflow.com/questions/12755539/why-is-singleton-considered-an-anti-pattern and https://stackoverflow.com/questions/1448393/singleton-design-pattern-pitfalls and https://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons – Slaw Dec 05 '20 at 06:34
  • And this: https://softwareengineering.stackexchange.com/questions/40373/so-singletons-are-bad-then-what – Slaw Dec 05 '20 at 06:37
  • 1
    Just a simple explanation - multiple users of the class overwrite each other's state ;) – Veselin Davidov Dec 05 '20 at 06:56

0 Answers0