0

At first glance, these seem equivalent. If one has the right visibility, one can access a global variable or a class variable from anywhere in the program; There is only one, shared copy of them. So why would a software engineer choose one over the other?

Considerations could assume a language like Python, with no private variables, or C++, with private variables.

1
  • The term 'global variable' is pretty overloaded. In Python the term 'global' refers to module scope, for example. Java doesn't support a true 'global' nor does it refer to anything as such. We also use 'global' less formally to mean a variable in some scope that is accessed and/or modified from many places in an program. I think you might want to clarify a bit here what specifically you mean by 'global'.
    – JimmyJames
    Commented Sep 21, 2022 at 19:26

2 Answers 2

4

Accessibility is not the only thing. There's also scope and context.

A class variable (or static member as they are called in many languages) is tied to a particular domain. It should make sense to make it a member of that class because it is meaningful in the context of that class.

Example: class Cat may have a static member count that keeps the number of Cat instances at any particular time. You could instead have a global variable catCount but that would be less OO. Obviously the number of Cat instances is closely related to the Cat class, hence it makes sense to make it a Cat class member. This also narrows the scope of the variable to the class members of Cat (you must type Cat. first for it to become available). Tight scope is always a good thing, a global variable catCount would be meaningless outside the scope of the Cat class and thus noisy.

1
  • I agree with much of this but OO purists don’t even recognize the need for classes, let alone hanging static members off of them. Try “less modern” or “less disciplined”. Commented Sep 22, 2022 at 0:42
0

It's about locality

A class defines a region of locality, within which things "belong together". Such locality is useful for understanding what relates to what (or does not).

Global variables do not give you this effect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.