Hey yo,
I’m not a big fan of constants.
It’s true in all project I’ve worked… they always comes in.
But it isn’t because I don’t like, I can’t bring new approaches to it, right?
Let’s say we’ve these fields to be shared as constants:
1 | |
The more common ways to make it as constants are:
- Creating an Interface, e.g.:
1
2
3
4
5interface Constant { String PROVIDER = "SomeProvider"; String SCHEMA_VERSION = "0.0.1"; String PRODUCT_VERSION = "V3"; }Personally I don’t like it ‘cause interfaces have another purpose to me.
- Creating a well known Utility Class:
1
2
3
4
5
6final class Constant { private Constant() {} public static final String PROVIDER = "SomeProvider"; public static final String SCHEMA_VERSION = "0.0.1"; public static final String PRODUCT_VERSION = "V3"; }A final class, private constructor, all public static… i don’t like it either.
- Creating Enum:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15enum Constant { PROVIDER("SomeProvider"), SCHEMA_VERSION("0.0.1"), PRODUCT_VERSION("V3"); private final String value; Constant(String value) { this.value = value; } String value() { return value; } }I like this one, but, create a new field, constructor, expose to a new method… nah, thanks.
I’ll bring my personal trick approach:
1 | |
No Interface.
No Utility Class(final class, private constructor, static things).
Just Enum.
Simple, concise and objective.
Another post, another real life scenario.
See ya!
xoff.