views:

82

answers:

2

If you have a class that has some named constants, what is the best practive for storing the constants:

Option 1: Namespace in Class header

So in my class header I will have:

class myClass
{
...
...
};

namespace NamedConstants
{
   const string Bucket = "Bucket";
}

Option 2 Member Constants

class MyClass {      // this goes in the class
private:                          // header file
  static const string Bucket;
  ...
};
// this goes in the class implementation file
const string MyClass::Bucket = "Bucket";

I actually prefer Option 1 as it is cleaner as variable name and value are together. Also, if you give the namespace a good name then it can make code more readable when you use constants:

TrafficLight::Green

Does anybody see any issue with this method over option 2?

+3  A: 

If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them private class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all.

If you put them into the class (or into namespace scope into the header), then all changes to their type and identifier will force clients to recompile their code.

If you put them into the class' implementation file, they are a private detail of the class' implementation and changes to them only force recompilation of the class' implementation.
If you put them into an unnamed namespace, they cannot collide with any other name:

namespace  {
  namespace NamedConstants
  {
     const string Bucket = "Bucket";
  }
}
sbi
Does the Unnamed namespace not make it "more global" (for want of a better word)
David Relihan
It makes it private to that implementation file.
Mark B
@David: Just so we don't misunderstand - that unnamed namespace would be in the class' __implementation__ file, not in its header.
sbi
@Sbi Good stuff - that has answered my question - Thanks
David Relihan
+1  A: 

Option 1 could lead to a separate string object for every file which includes the header. So it depends among others on how scarce your resources are.

Peter G.
However, if I put in CPP file I won't have this problem right?
David Relihan
@David Relihan exactly
Peter G.