Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global constants in separate file. Is it a good idea?

I'm currently working on ASP.NET MVC application. I'm planning to create a static class where I plan to hold all the global string constants like session names.

The reason I'm hesitant is because it's kind of smell but I'm not aware of better alternative.

Please show me the light how to define global constants.

like image 935
Vadim Avatar asked Nov 21 '25 20:11

Vadim


2 Answers

vadim,

i do exactly as you propose and use a static class for this purpose. You then get the advantage of strongly typed accessors PLUS the ability to add overrides (in the form of methods), should you require them.

here's a snippet:

public static class Config
{
    private const string NotSet = "**VALUE NOT SET**";
    private const int pageSize = 5;

    public static string CustomCache
    {
        get
        {
            return ConfigurationManager.AppSettings["CustomCache"] ?? NotSet;
        }
    }

    public static int PageSize
    {
        get
        {
            // simple default - no setter
            return pageSize; 
        }
    }
}

typical usage:

items = _repository.GetPaged(pageNumber, Config.PageSize)

in the above class, some settings are called '2nd generation' from the app settings in the web.config but with strong typing in the classes to ensure runtime error checking etc.. others are purely static settings defined in the class.

it's the flexibility to do all of the above that (in my opinion) gives this approach both appeal and a real strength.

like image 105
jim tollan Avatar answered Nov 23 '25 14:11

jim tollan


Another alternative would be to create a resources (.resx) file. Or if these are configurable values, they can go in web.config or a database configuration table.

like image 21
Otávio Décio Avatar answered Nov 23 '25 14:11

Otávio Décio