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.
I'll give you a few tips on managing enums.
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.
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.
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:
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
For example, if you have some shared preferences keys as constants (which you should), make a SharedPreferencesKeys
class and put them in there.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With