Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Class That Has 90% Static Members. Good Practice Or What?

Tags:

java

oop

static

I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.

The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?

I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.

like image 792
Aaron Avatar asked Dec 13 '22 06:12

Aaron


2 Answers

As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.

In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.

ADDED

I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.

There is no perfect fix, YMMV, but I'd consider a single static method, something like

   World World.getWorld(String name)

and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".

Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)

like image 156
user949300 Avatar answered Feb 08 '23 22:02

user949300


It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.

Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.

like image 45
Aravind Yarram Avatar answered Feb 09 '23 00:02

Aravind Yarram