Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aren't fields in classes similar to global variables?

I started learning a functional programming language(SML) and programmed in this language a little bit. And then i went started checking Java and i had this feeling that class fields seem like global variables and they complicate programming. For example i must read methods to see which one read/write them etc.

From what i have heard using global variables in programming languages like C is a bad idea. But what about Java class fields, aren't they something like global variables for all your class methods? Is it a bad idea to use fields? (Or maybe i have understand something wrong or i program in the "wrong way" Java)

like image 866
Marin Bauer Avatar asked Feb 03 '23 00:02

Marin Bauer


2 Answers

I assume by "class variables" you mean "static variables".

You ask "aren't they something like global variables for all your class methods?".

Yes, you are right. Within the class the behave like globals with all their issues.

The difference is that your classes should not be as complex as whole programs and thus it would be easier to understand and fix the problems caused by them.
The less code can modify a variable the less cases you have to consider. Globals can be modified by arbitrary unknown code.

It also makes absolute sense in some situations to have all instances of a class share a variable (e.g. a singleton). You just have to use it responsibly.

Should you not use them?
No, you can use them. But limit their visibility to the needed minimum so they don't become 'de facto' globals.
Also make them final if possible.

like image 140
zockman Avatar answered Feb 05 '23 14:02

zockman


Class level variables are global variables in the context of the class. That is done to keep some state, you need to have them somewhere. In some cases, Class level variables are considered bad practice though especially when they are not immutable.

like image 32
fastcodejava Avatar answered Feb 05 '23 14:02

fastcodejava