Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to create a Constants class with large number of static fields?

Let's say I have a constants class containing 200+ static fields :

class AnimalConstants {
  static final int AARDVARK = 1;
  static final int ANTELOPE = 2;
  static final int BEAR = 3;
  ...
  ...
  static final int ZEBRA = 200;
}
  • Can anyone explain if there are any negative impact on performance and memory from using such classes.
  • Would it be better or worse if the class is changed to an interface (e.g. SwingConstants) and being implemented by some classes?
  • Would it be better or worse if I implement the constants as an Enum class?
like image 582
Augustus Thoo Avatar asked Dec 09 '22 18:12

Augustus Thoo


1 Answers

I don't think the impact is performance or memory.

I think it has to do with things like readability of code, keeping constants close to where they're used, and fundamental understanding of your problem.

I prefer to declare constants closer to where they're used. I believe they're easier to understand that way.

I would be surprised if the real constants that you claim number 200+ are truly related. If they are, they belong together in one place. If not, I'd say that they should be broken into smaller pieces and declared closer to where they're used.

I'll bet there's more context than your contrived example that would change responses if known.

Sure , enums are great. But see my other comments first.

like image 132
duffymo Avatar answered Dec 11 '22 08:12

duffymo