Question

Example 1 (used at the moment)

If (BodyPart["Right Leg"].BodyStatusEffects["Active"].Active)
{
    BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"].Active = false;

    BodyPart["Torso"].BodyStatusImpacts["Poisoned"] = 
        BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"];

    BodyPart["Right Foot"].BodyStatusImpacts["Poisoned"] = 
        BodyPart["Right Leg"].BodyStatusImpacts["Poisoned"];
}

Example 2

BodyPart.[BodyParts.RightLegs].BodyStatusImpacts["Poisoned"].Active = false;

Which of these two examples is the preferred method? Is there a 3rd way that is even better?

Was it helpful?

Solution

I would generally recommend using enums in this situation. Reasons:

  • It defines very clearly what is allowed and what is not allowed in the structures that are keyed with them, if you define the enum type as the key.
  • Your IDE will probably give you auto-complete functionality which is easier and faster than typing an open-quote, typing a string, then a close-quote.
  • If you ever need to generate a list of all keys used in your program, it is much easier to iterate over an enum than to search for all references to the underlying data structure and then find all the different string keys you used.
  • It's relatively easy to type the wrong string as a key and then waste time trying to figure out why your program won't work. Can't make that same mistake with an enum.
  • If you ever need to change an enum value, your IDE will probably let you refactor it very easily. With strings as keys, you'll be doing a lot of find-and-replace on the text and hope you got it all.

One problem with enums is that you can't add new values to an enum at runtime (at least I don't know of any way to), so if your program will need to be able to create entirely new keys based on user input at runtime, enums can't help you with that. But you could key your data structure with "soft" enums (the string values of the enums) and user-entered strings to get a sort of hybrid solution.

OTHER TIPS

I see no code here that uses enum as a key. If you were hoping for type safety this isn't the way to find it.

Consider:

Dictionary<SomeEnum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();

aDictionary[SomeEnum.RightLeg]

The limitation here is now key's must be known statically. No sneaky taking arbitrary keys as input and using them to find things later. There are cases where using strings as keys is very useful. But you must guard against issues of uniqueness and typo's that enum's would take care of for you.

When you use code like:

BodyPart[BodyParts.RightLegs.ToString()]

you're getting a canned string. It's using enum to get a string to use as a key. Anyone is free to send a literal string into that dictionary at any time. Maybe that's good enough for you but it's not using enum as key. You aren't getting type safety.

Licensed under: CC-BY-SA with attribution
scroll top