Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not good to write to static field from instance method in Java?

I have found a post here in SO discussing the code change required to prevent writing to a static field from an instance method but why is not a good practice to do so ? Why did Java designers allow this then ?In other words why does the compiler not throw an error when some one attempts to do this ?

like image 323
Inquisitive Avatar asked Jul 04 '12 08:07

Inquisitive


1 Answers

In the words of the 'findbugz' documentation:

This instance method writes to a static field. This is tricky to get correct if multiple instances are being manipulated, and generally bad practice.

Which is to say it isn't always wrong, simply that it is something that is often a source of errors. Instance objects manipulating static fields can be useful for example for lazy initialization of shared objects, so it is not always wrong, but it can be hard to get it right (particularly if multiple threads may be running at the same time).

like image 186
Jules Avatar answered Oct 13 '22 07:10

Jules