Posts: 323
Threads: 241
Joined: Oct 2012
07-26-2014, 04:34 PM
(This post was last modified: 07-28-2014, 01:49 PM by Vuhelper.)
[SIZE="3"]CS201 Introduction to Programming GDB No.1 Solutions and Discussions Spring 2014 Due Date 8th August 2014[/SIZE]
[SIZE="3"]GDB topic:
Is it more expensive to use too many static variables instead of ordinary variables? If yes, then how?
Your answer must be concise and not be more than 200 words.[/SIZE]
Posts: 9,583
Threads: 8,089
Joined: Apr 2011
It's not a problem. However, it is generally accepted good design practice to limit the scope of every variable so that it's as wide as it needs to be - but no wider ;-)
This means that:
- you don't use a method local variable as the controlled variable of a for loop, if you can declare the controlled variable in the for loop heading.
- you don't use a class global variable (field) inside a method if you can instead use a local variable declared inside the method.
- you don't declare a field public if it can be protected, nor protected if it can be private.
- you don't declare a field static if it can be non-static.
- class level "final" values should be declared static.
In my experience as a Java programming teacher, most students have difficulties with the second option, and will tend to declare a lot of class global fields for variables should have been declared local.
Posts: 323
Threads: 241
Joined: Oct 2012
Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.
I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.