4
\$\begingroup\$

I'm making a game for Android using Android Studio with Libgdx in Java. In my game there are main object like Screen, ObjectFactory, SoundPlayer, Painter (Responsible for drawing) and a few more. 'til now I passed them to each GameObject that uses them but then I realized I could just make them static and every GameObject who needs them will just call them statically. I wonder if I make these main objects static, would it hurt the performance? Because it seems like such a comfortable solution... Thanks in advance.

\$\endgroup\$
9
\$\begingroup\$

It won't hurt performance. It might in fact be (very, very negligible) faster because you save the overhead of passing these objects to the game objects.

The reason static classes are often frowned upon is that their static properties are global variables and globals cause all kinds of problems architecture-wise. For example, when you ever decide you might require more than one Screen, ObjectFactory, SoundPlayer or Painter object, you will have a hard time refactoring your application to allow that. Another problem is that you can't initialize these objects as soon as they are created, because they are always around. That means you need to keep in mind which one is already initialized and which one is not, which can cause quite a headache when they have dependencies on each other.

But if these reasons are not convincing for your particular project, there is nothing wrong with static classes.

\$\endgroup\$
3
\$\begingroup\$

If you're definitely only ever going to have one instance of these objects, and presumably you are, then this would be a better way to go. However, maybe a better solution would be to use the Singleton pattern, and (for example) create a static GetScreen() method in the Screen class that any other class can call to obtain the single instance of the Screen class.

\$\endgroup\$
  • \$\begingroup\$ Keep in mind that many consider it an anti-pattern because they may. But I have used it in the past without big problems in small projects. \$\endgroup\$ – MVCDS Apr 28 '16 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.