I am making a program which makes use of a couple of constants. At first, each time I needed to use a constant, I'd define it as
//C#
private static readonly int MyConstant = xxx;
//Java
private static final int MyConstant = xxx;
in the class where I'd need it. After some time, I started to realise that some constants would be needed in more than one class.
At this time, I had 3 choises:
I ended up implementing my code with the second option. Is that the best alternative? I feel I am probably missing some other better alternative.
What worries me about using the singleton here is that it is nowhere clear to a user of the class that this class is using the singleton. Maybe I could create a ConstantsClass that held all the constants needed and then I'd pass it in the constructor to the classes that'd need it?
Thanks
edit: I'm using this mostly for complex types, not ints and strings. At least in the C# case that makes a difference as it means I can't use the const
keyword.
No wording about C#, but in Java there are several ways to solve this problem.
Change the access modifier to default (package-only) or public
. The most straightforward solution.
Group them in a package-private or public
enum
. Most straightforward if those values are related to each other. E.g. Role.ADMIN
, Role.USER
, Role.GUEST
, etc.
Declare them in a package-private or public
interface
and let the classes implement it. Only do this if those constants belong to some contract the classes have to adhere as well.
Put them in properties files and load as private static final Properties
and add a public static String getProperty(String key)
. Wrap this in some package-private or public
Configuration
class. More useful if those constants might be sensitive to changes which you could then control externally.
Constants doesn't require to be accessed by an instance, so the whole singleton idea makes no sense.
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