2

It is desirable to have constants (e.g. certain strings or numbers) to be defined at some central point. In order to keep readability of the code well, it is also desirable have easy access to those constants. During my research for good practices to achieve this I have now found the following two solutions (https://stackoverflow.com/a/9649425/2776093).

FoodConstants.h:

namespace FoodConstants {
    namespace Fruits {
        extern const string Apple;
        ...
    }
    ...
}

FoodConstants.cpp:

namespace FoodConstants {
    namespace Fruits {
        const string Apple = "apple" ;
        ...
    }
    ...
}

FoodConstants2.h:

class FoodConstants {
public:
    class Fruits {
    public:
        static const string Apple;
        ...
    }
    ...
}

FoodConstants2.cpp:

const string FoodConstants::Fruits::Apple = "apple"
...

For both solutions I can access the the apple constant with FoodConstants::Fruits::Apple anywhere in the program where the .h is included. Initialization is done in the same compilation unit and initialization problems are avoided. I have noticed one difference: For the second solution I can't, e.g., do a "using namespace FoodConstants" to abbreviate the access to the string constant with Fruits::Apple.

Are there any other differences? Is there a preferred way to organize constants like this?

Community
  • 1
  • 1
mxenic
  • 41
  • 2
  • 1
    Another difference is that if `Fruits` is a class, you can pass it as a type template argument, which can't be done for namespaces. – Angew is no longer proud of SO Sep 13 '13 at 13:08
  • If you're just going to have a class containing other classes, then make it a namespace. The same if you're going to have a class with just public variables. Classes are mostly meant to instantiated into state-full objects. Also, classes can be used as types, which a namespace can't be. – Some programmer dude Sep 13 '13 at 13:09
  • *It is desirable to have constants to be defined at some central point.* Disagree with the premise. – David Rodríguez - dribeas Sep 13 '13 at 13:14
  • "It is desirable to have constants that belong together (like the constants for the Fruits) grouped together at some point". That is what I actually meant. It is not desirable to have all the constants at some central point. Agree now? – mxenic Sep 13 '13 at 13:33

1 Answers1

0

Are there any other differences?

Yes, there are. I can see two:

  1. Using the class solution you can control accessibility (public/protected/private) which is not possible with the namespace solution.

  2. Using namespace you can split the declarations across several files while this is not possible with the class solution since the class definition (which contains the declarations of all members) must be given in a single file.

Cassio Neri
  • 19,583
  • 7
  • 46
  • 68