Konrad Viltersten
Konrad Viltersten

Reputation: 39250

Is there a general approach to enums within enums?

Disclaimer. I'm not sure if the title is the best one. I couldn't think of a better one that wasn't miles long. Please feel free to suggest an improvement.

When a programmer is designing a set of states, it's natural to apply enumerations. In case of e.g. weekdays, it's obvious, traditionally accepted and straight-forward. However, sometimes, we also need to set the reason of the status as e.g. task management. We can have states as follows:

enum Status { New, Active, Inactive }

but still require to have a status of the status, a stage of the status or maybe a reason of the status. Normally, I'd add a bunch of new enumeration like so:

enum StatusOfNew { UnseenYet, RefusedToEvenLookAtAndOrQuitTheJob }
enum StatusOfActive { Assigned, Commenced, BeingTested }
enum StatusOfInactive { Done, Trashed, GivenUpOnBecausePeopleKeepQuittingTheJob }

An alternative approach would be to have a long list of all the combinations in the following way.

enum Status
{ 
  New_UnseenYet, New_RefusedToEvenLookAtAndOrQuitTheJob,
  Active_Assigned, Active_Commenced, Active_BeingTested,
  Inactive_Done, Inactive_Trashed, Inactive_GivenUpOnBecausePeopleKeepQuittingTheJob
}

Then, we have the classy approach, where each state is its own type with a common superclass and specific stages/reasons.

class New : Status
{
  enum Reason
  {
    UnseenYet,
    RefusedToEvenLookAtAndOrQuitTheJob
  }
}

I can wage them against each other considering the relation between complexity of implementation, cost of maintenance and gain in robustness. However, I wonder if there's other methods to consider, syntaxes to apply or approaches that void the problematic all together.

Mainly, as a MS monkey I want to see a language specific solution in C#. However, being a curious and open-minded creature, I'd welcome suggestions from other lingos, as well. I've tried to ask this question on Programmers but, apparently, my questions are too dumb and the site told me to duck off (no profanity intended, the typo is intentional and I love ducks).

Upvotes: 0

Views: 26

Answers (1)

user1531971
user1531971

Reputation:

Keep it simple. This is really a state and a reason. But how your code gets at either should drive your design.

If you expect to have state model for both, then you might need nested enums. Otherwise, a class or class/enum configuration makes more sense.

The aim is to have readable, maintainable code. Enums are there for safety and readability. So the decision is one of appropriateness in context.

That is, there is no top down natural better. All your approaches are valid in the right context.

Upvotes: 1

Related Questions