-3

I like using enum class to avoid hard coded values as much as possible but it's a little bit more complicated when it comes to strings. I have a design I'd like to share that I feel is a little bit bulky and I would love some ideas on how to simplify it.

class StringDefinition
{
private:
   StringDefinition(const std::string &def);

public:
    bool operator==(const StringDefinition&rhs) const;

public:
   static const StringDefinition StringDefinitionOne;
   static const StringDefinition StringDefinitionTwo;
   static const StringDefinition StringDefinitionThree;

public:
   std::string ToString() const;

private:
   string stringDef;
};

StringDefinition::StringDefinition(const std::string &stringDef)
{
   this->stringDef = stringDef;
}

const StringDefinition StringDefinition::StringDefinitionOne("One");

etc...

All ideas and comments are welcome.

Edit: I am not using string literals because it does not force the developer to use a value from a definition list. They can still hard code a string even when you expect them to use your string literal. If I'm doing something crazy, I'd love some constructive criticism rather than just down voting the question.

Pittfall
  • 2,751
  • 6
  • 32
  • 61
  • What does this bring over just a named global string literal? – Borgleader Jan 31 '17 at 20:44
  • I don't want to just make an object with const strings because then the type is string. Anyone can still hard code a string. Say I create a method and I want a StringDefinition passed in, I can do that. If I use a string literal, someone can pass a hard coded string – Pittfall Jan 31 '17 at 20:44
  • A `std::tuple` maybe? – πάντα ῥεῖ Jan 31 '17 at 20:44
  • Why wouldn't you use const char * variables? – Anon Mail Jan 31 '17 at 20:45
  • 1
    @Pitfall what's to prevent someone from making their own StringDefinition and passing it in? – Anon Mail Jan 31 '17 at 20:47
  • @AnonMail They can do this but now they are making a conscious decision to modify a library. With a string literal, a developer may not be aware that it exists. – Pittfall Jan 31 '17 at 20:50
  • 1
    Use enums to enforce values. Input strings from the external world (e.g. files or database) should be converted to/from enums. – Anon Mail Jan 31 '17 at 20:54
  • @AnonMail you cannot use an enum for strings so you'd need a mapping database table that has an id and a value. Sure, if you want to dig deep, you can argue the database design but it would take an arrogant newbie to suggest a rewrite. Not saying this is you, I'm just saying that perfecting the design is not always an option. – Pittfall May 05 '17 at 16:25

1 Answers1

0

This is question of personal taste, but how about keeping it a little more simple; something along the lines of:

enum class Foo { Ack, Eek };

explicit operator std::string(Foo foo) {
    static const char* const names[] = { "Ack", "Eek" };
    return names[(int)foo];
}
Cameron
  • 96,106
  • 25
  • 196
  • 225