Singletons and constants

Posted by devoured elysium on Stack Overflow See other posts from Stack Overflow or by devoured elysium
Published on 2010-05-02T21:50:56Z Indexed on 2010/05/02 21:58 UTC
Read the original article Hit count: 134

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:

  1. To define them in the different classes that needed it. This leads to repetition. If by some reason later I need to change one of them, I'd have to check in all classes to replace them everywhere.
  2. To define a static class/singleton with all the constants as public.
  3. If I needed a constant X in ClassA, ClassB and ClassC, I could just define it in ClassA as public, and then have ClassB and ClassC refer to them. This solution doesn't seem that good to me as it introduces even more dependencies as the classes already have between them.

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

© Stack Overflow or respective owner

Related posts about singleton

Related posts about object-oriented-design