开发者

Why no global variables in java like C++?

开发者 https://www.devze.com 2022-12-18 14:42 出处:网络
Why there are no global variabl开发者_JAVA技巧es in java? If I like to use any variable in all classesof a program then how can I do that?If you really want to do that, make it a public static variabl

Why there are no global variabl开发者_JAVA技巧es in java? If I like to use any variable in all classes of a program then how can I do that?


If you really want to do that, make it a public static variable.

However, you'd be advised to try not to - it makes for less elegant, harder to maintain, harder to test code.


Global variables (in the Java context - public static variables) are bad, because:

  • harder to maintain - you can't put a breakpoint or log each change to a variable, hence unexpected values at runtime will be very hard to track and fix

  • harder to test - read Miško Havery's post

  • harder to read - when someone sees the code he'll wonder:

    • where does this come from?
    • where else it is read?
    • where else it is modified?
    • how can I know what's its current value?
    • where is it documented?

To make one clarification that seems needed - variables != constants. Variables change, and that's the problem. So having a public static final int DAYS_IN_WEEK = 7 is perfectly fine - no one can change it.


Some valid global "variables" are constants ;-) for example: Math.PI


C++ is multi-paradigm, whereas Java is pure "almost exclusively" an object orientated. Object orientated means that every piece of data must be inside of an object.

Please see the links for more information.


Why globals are evil, explained here.


If you need a certain resource that is accessed from any part of your program, have a look at the Singleton Design Pattern.


I just wanted to add that if you want to use a constant global variable its safe. To use it use the final keyword. Example:

public static final int variable;


Global variables do not jive well with OOP. Still one can have constants as global variables. In a sense, singleton are global variables. If you want to have constants as global variables it is better to use enums in stead.

EDIT:

Constants which used to invoked as Class.Constant now can used Constant by using static import. This comes as close as possible to global variables in C++.


package foo;
public class Globals {
  public static int count = 3;
}

Then, you can access it anywhere as

int uses_global = foo.Globals.count + 1;


Java is intended to make fully-portable, fully-reusable objects.

By definition, something that depends on a "global variable" is not fully portable or fully reusable. It depends on that global variable existing on the new (reusing) system, and it depends on code on the new (reusing) system manipulating that global variable. At that point, you're better off putting that global variable into an object of its own.

0

精彩评论

暂无评论...
验证码 换一张
取 消