Search code examples
c++enumscode-duplication

Reducing code duplication when using enums in model code with respects to database and GUI


I have an enum in one of my model classes so i don't have to worry about wrong values being passed into it.

The problem i have is that i have a lot of code duplication throughout my code because of said enum. Whenever i want to change the enum i also have to change these parts of my code to make the whole thing work:

  • Change the enum itself
  • Change the SQL table definition (I use MySql enums)
  • Change the enumToString translation table in my data access layer (i need the string for the sql query)
  • Change the stringToEnum translation table in my data access layer (to convert the retrieved value back to the correct enum entry)
  • Change the enumToPrettyString translation table for my GUI usage (display a human readable String instead of the database stored one)
  • Change the list of all available enum entries so i can fill a dropdown-box in my GUI with all possible entries for the user to select

I know that Javas Enum classes are more powerful and you could add a lot of this information directly in the enum entry definition, but C++ enums are just integers internally, so i don't get that convenience.

Any ideas how i could minimize code duplication here?


Solution

  • This is a good candidate for code generation. Write a single specification for your enumeration and then generate all required translation code from it across all your language environments. Leverage your build system to keep everything up to date. The main pitfall is that if you ever store or serialize the low-level integer representation you need to be careful never to remove / repurpose any enum constructors (just add new ones at the end instead).