Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right place to keep Constants and Enums? [closed]

Tags:

java

android

In application development, I often need to use 'Constants' and 'Enums'.As far as I use the strategy, I keep all 'Constants' in a separate class named 'Constants' but I am not sure whether I should keep all Enums in a separate class as I use 'Constants'? or I should keep Enums in those class where I needed? Or should I also keep Enums in Contants class as 'static'.My question is what is the right place to keep all constants and Enums.

like image 615
Abdul Waheed Avatar asked Dec 25 '22 04:12

Abdul Waheed


1 Answers

I'll give you a few tips on managing enums.

  1. Place enums in its own file.

Since enums are usually kinda small and you won't write a lot of code in it, it's very easy to miss it if you put it in the same file as other code. If you put it in its own file, you just need to look for the name of your enum in the file explorer, which IMO is way easier than looking for it in code.

  1. Make good use of packages.

Don't just put all enums in the same package (e.g. yourapp.enums) unless they are related. Just like you do with classes and interfaces, you put enum files in suitable packages. Alternatively, you can put enums in a sub package of the suitable package. For example, a Color enum can be put into yourapp.graphics.enums package. This just makes it a whole lot easier to find them.

  1. Place enums that are very closely related in one single file.

That just makes sense, right? If enums are closely related, you often need to edit them or add some methods or whatever. Therefore, it is convenient to put related enums together so you can easily edit them without opening a new file.

EDIT: I didn't notice that you also wanted to know where to store constants. Here are some more tips:

  1. If a constant is only used in one class, declare the constant in that class.

C'mon, this is obvious. If a constant is only used in one class, it probably shouldn't be exposed to the world. Like, it just makes more sense. So, remember to declare those kinds of constants as private static final in the same class

  1. If a constant is used in multiple classes, try to classify these constants.

For example, if you have some shared preferences keys as constants (which you should), make a SharedPreferencesKeys class and put them in there.

  1. Again, use packages

This is basically the same idea as enums. Always use packages to classify your things.

Nevertheless, these are only some of my own habits. If you don't like them, it's fine.

like image 163
Sweeper Avatar answered Feb 16 '23 06:02

Sweeper