Andrei Meși Andrei Meși - 4 months ago 8
Java Question

Java: instance really better than static?

So I have a few classes like

MainWindow
,
MenuPanel
,
GamePanel
,
GameEngine
,
Player
and so on...

My question is, although I've read much about static vs instance, which should be more recommended to use, according one of my lines looks like this:
MainWindow.getGamePanel().getPlayer1().getName().toLowerCase().compareTo(...);


or
MainWindow.getGamePanel().getLabels()[0].getIcon();


Do you think this is a good practice trying so hard not to use statics where every object has different properties and things are not generalized, instead of maybe declaring the
labels
or the
players
and
names
static and having a much more easy to reuse and read code?

The idea is I used these long codes because surely it would be awkward to create a
GamePanel
(visual class) object in the
Player
(more like a logical) class for example. So I just created like one object of every class in
MainWindow
(not the main class, just the JFrame class) and created
static getters
for every one of them.

Answer
MainWindow.getGamePanel().getPlayer1().getName().toLowerCase().compareTo(...);

This is a classic violation of the Law of Demeter, sometimes expressed as "ask, don't look." The class calling these getters has too much knowledge of the overall structure of the program, which makes it brittle. If the relationship between any of these classes changes, all the code that relies on these chained getters will break.

The idea behind "ask, don't look" is that the class calling these getters to get the player name should instead require the player name as a constructor parameter. If that leads to a constructor with a huge number of parameters, the class is probably violating the Single Responsibility Principle.