Tuesday, 24 June 2014

Why there are no global variables in Java?

- -   The global variables breaks the referential transparency

- -   Global variables creates collisions in namespace.
- -  Global variables are usually a design flaw.
- - Your components should be self-contained and should not need any global state.
Instead, use private static fields.
- - 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.

No comments:

Post a Comment