Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad to create a public static object

Tags:

java

object

Is it bad to declare an object like this

     public static GUI g = new GUI();

or should I avoid creating a public object when I want multiple methods to be able to use the same object?

like image 498
Peter Chappy Avatar asked Jan 26 '26 14:01

Peter Chappy


2 Answers

Yes, it is generally bad to expose an object as a public static variable, because everybody has a write access to it. Making the variable final make it slightly better, but the best solution would be to make your variable private, and provide a static getter.

like image 78
Sergey Kalinichenko Avatar answered Jan 29 '26 11:01

Sergey Kalinichenko


Static state is generally considered untestable, and bad. Every static object is an implicit input to everything you're trying to test, and tests are all about controlling the inputs and experimenting how your methods behave in response to precise parameters.

Instead, you should pass an explicit reference to the GUI object to every class that needs it. There are a number of ways to simplify the bookkeeping involved; typically involving dependency injection.

like image 38
Louis Wasserman Avatar answered Jan 29 '26 11:01

Louis Wasserman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!