Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables inside instance methods - How to fix that?

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
like image 332
Viet Avatar asked Aug 10 '12 02:08

Viet


People also ask

Can static variables be changed in instance methods?

Static methods cannot access or change the values of instance variables or the this reference (since there is no calling object for them), and static methods cannot call non-static methods. However, non-static methods have access to all variables (instance or static) and methods (static or non-static) in the class.

Can we declare static variable inside method?

We cannot declare static variables in the main method or any kind of method of the class. static variables must be declared like a class member in the class.

How static methods can access instance variables?

A static method cannot access a class's instance variables and instance methods, because a static method can be called even when no objects of the class have been instantiated. For the same reason, the this reference cannot be used in a static method.

Can static variables be instance variables?

Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block. As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.


1 Answers

  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.

like image 141
Sergey Kalinichenko Avatar answered Oct 09 '22 10:10

Sergey Kalinichenko