From Wikipedia:
In object-oriented programming with classes, a class variable is a variable defined in a class (i.e. a member variable) of which a single copy exists, regardless of how many instances of the class exist.
Seems useful. But not everywhere. In fact, depending on the language you’re using, you even might want to avoid them.
As an example of bad use of class variables, I recently stumbled upon a Java implementation of the Minimax algorithm.
/** A Minimax instance represents a single AI entity. */ public class Minimax { /** Default depth used by the algorithm. */ private final static int MAXDEPTHDEFAULT = 4; /** Actual depth used by an instance of Minimax. */ private static int maxDepth = MAXDEPTHDEFAULT; // Constructor, a method executed when creating a new instance. public Minimax(int depth) { // Other parameters are omitted for simplicity maxDepth = depth; // ... } }
(Note: in Java, a variable marked as “static” is a class variable.)
The depth is the number of turns the AI entity can see in advance. It can be viewed as the toughness of an entity: the greater the depth, the farther in the future the AI will be able to see, and the harder it will be hard to beat.
Nothing wrong with MAXDEPTHDEFAULT, because it’s a constant (by the
way, the concept of “constant variables” is rather funny). But
maxDepth will annoy us. Why? Because we won’t be able to create
multiple AI entities with different depths. If we want to watch two AI
entities playing against each other:
ai1 = new Minimax(4); ai2 = new Minimax(6);
The two AI entities, ai1 and ai2, will use a depth of 6. Yeah,
even ai1. We can’t test if an AI with a high depth will effectively
beat an AI with a low one. We can find worse situations where this
kind of class variable is defined in an interface, impeding other
programmers' work.
And the solution, in this case, is simple: just remove the static
keyword from maxDepth.