5

Recently I inherited 10 year old code base with some interesting patterns. Among them is static variables inside instance methods. Only single instance of the class is instantiated and I can hardly find reason to justify existence of those static variables in instance methods.

  1. Have you ever designed instance methods with static variables? And what are your rationales?

  2. If this pattern is considered bad then how to fix it?

Note: This question is not relevant to Static variables in instance methods

EDIT:

Some reading:

  1. static class and singleton
  2. http://objectmentor.com/resources/articles/SingletonAndMonostate.pdf
  3. http://www.semantics.org/once_weakly/w01_expanding_monostate.pdf
Community
  • 1
  • 1
Viet
  • 17,944
  • 33
  • 103
  • 135

3 Answers3

4
  1. This is a classic C++ implementation of the singleton pattern, described in one of Scott Meyers C++ books.
  2. Singleton is a controversial pattern, so there is no industry-wide consensus on singleton being good or bad.

An alternative to singletons is a purely static objects. This question has a good discussion.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • +1 thanks. I found this: http://stackoverflow.com/questions/720744/static-class-and-singleton – Viet Aug 10 '12 at 03:19
  • Also I deduced from your answer: If ppl can't decide between good & bad => the technique is controversial :P – Viet Aug 10 '12 at 03:29
2

About the only time I've used static fields in an instanciable class has been as constants.

Generally speaking, you would want to create your class to be either entirely static, or entirely instanciable (with perhaps the exception of constants which you may want to keep static). With a singleton class they will behave in much the same way. The danger of mixing the two techniques is if you decide to make the class no longer a singleton, you might run into some strange behaviours in your now multi-instanced class.

chrisduran
  • 29
  • 2
2

Having a static variable is useful in a procedural function as it can serve as a kind of global variable with limited scope.

The only reason I can see to do something like this in a method would be to have the variable persist over many calls without having to declare a member variable that serves no other purpose. Honestly, I feel like this is just lazy programming and should be avoided.

VoidStar
  • 581
  • 3
  • 6