开发者

How to handle global string constants ASP.NET MVC

I have a new MVC 3 project, and in it I use model annotations like:

[DisplayFormat(NullDisplayText = "[Not set]")]

I prefer to avoid duplication of the string literal using something like this:

[DisplayFormat(NullDisplayText =  GlobalStrings.Nulls.DefaultNullText)]

where:

public struct GlobalStrings
{
    public struct Nulls
    {
        public const string DefaultNullText = "[Not set]";
 开发者_JAVA技巧   }
}

But I can't help feeling there is a better way of doing this?


What you're doing is not a terribly bad thing - you are sharing your constants in a single easily-altered location, which is a very good idea.

Using a single GlobalStrings struct is also not that bad an idea, if the strings in this place are truly global (used in many locations throughout your program). This isn't usually the case though (aside from truly global text like maybe ApplicationName and Publisher).

The strings are usually likely to be used in a more localised part of your application (e.g. a subsystem). You could consider using another simlar struct for the "globals" for that subsystem alone. If the strings are needed only within one class or a hierarchy of classes, then consider putting them in the base class. If you put each of your "global" strings into the class to which it most relates, it helps to categorise and relate constants to the area in which they are applicable. So if the "default null text" actually only applies to data you retrieve through your 'DataAccess' class and users of that class, then consider adding it as a public const/property of the DataAccess class, so that clients of that class can access the "global" as DataAccess.DefaultNullString - this makes it clearer to other programmers what the usage of that constant is.

By including constants within a class they are technically still available "globally", but are not "global" in the evil sense ("here is a constant but I don't have any idea where in the program it applies")

You'll find that if you embed your constants into different classes/subsystems in this way, your GlobalStrings struct will become very small or even empty.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜