What is the best way to avoid magic keys? Using string constant keys in a class or using an enumeration?

My idea is to avoid magic string keys in my ASP.NET MVC application. To do this, I want to create string constant keys for sharing in the application.

For example, I can write TempData[MyClass.Message] or TempData[MyEnum.Message.ToString()] instead of TempData["Message"] .

 public class MyClass { public const string Message = "Message"; } 

and

 public enum MyEnum { Message, Others } 

My questions: What is the best way to avoid magic keys? Using string constant keys in a class or using an enum with ToString() ?

+8
c # asp.net-mvc
source share
3 answers

It depends on preference and use.

You can take the listed values โ€‹โ€‹in a strongly typed way:

 public void SomeFunction(MyEnum someValue) { } 

or

 TempData[MyEnum.Message] 

With constant strings you cannot.

You also have a built-in way of listing the values โ€‹โ€‹in an enumeration.

There is a third option that you did not present, and this means that your โ€œconstantsโ€ are in your configuration settings (App.Config). This will allow you to customize them after compilation. You may not need it now, but you can in the future, so itโ€™s worth considering.

One of them might be better for globalization. I am not sure, since I have never globalized the application. I believe this works in satellite assemblies.

Basically, it comes down to what TempData is, and how you intend to use it.

+5
source share

You should use constant strings as they may contain spaces / special characters if these are your requirements. Otherwise, change TempData to Dictionary<MyEnum,object> , which works best.

+5
source share

I know this was answered, but I want to drop my thoughts here. You are too careful about the mechanics and not the problem you are facing - "how can I avoid breaking my application when I decide that TempData [" Message "] should be a session [" Alert "]" (or that something like that.

Magic strings do not apply to dictionary keys โ€” they apply to messages sent to a routine that do something based on a string value. Something like "SetStatus (" current ")" would be magical.

What you want to do is use a centralized message processing method. Create a helper class for yourself and name it "Messaging", if you want - I get all Railsy and call it "Flash". Then you can do something groovy like โ€œFlash.Message (โ€œ Hello there โ€)โ€ - this hides the mechanism (as it should be) and you donโ€™t worry about these dumb dictionary keys.

You can also expand this - "Flash.Alert (" Oh NO! ")" Etc.

+2
source share

All Articles