Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid hardcoding strings

This is a question regarding best coding practices. I would like to know the consensus about how to best avoid hardcoding strings and values in a .NET application. What I've seen so far where I have previously worked:

  • using resource .resx files
  • storing these values and strings in App.config or web.config
  • making a static class ApplicationStrings and declaring all the strings and values in there:

    public static class ApplicationStrings
    {
        #region constants
        public const string APPLICATION_NAME = "X";
        public const string APPLICATION_RESOURCEMANAGER_NAME = "ResourceManagerX";
        public const string APPLICATION_DEFAULT_LOGFILENAME = "log.txt";
    }
    

However, is not the 3rd method, just another hardcode? Does it make sense to have such a class? The benefit would be that all strings are in one place, but is that really avoiding a hardcode?

Also, if you have developed other habits for this situation, feel free to post.

like image 877
Amc_rtty Avatar asked Jul 16 '11 22:07

Amc_rtty


1 Answers

The main benefit is indeed to have all strings in one place and you only need to change it there to update the whole program. If different parts of your program use the same string and one instance gets updated, but another not, then you have a problem. This holds true for all literals, by the way.

And then with resource files there is the benefit of i18n and l10n. If you need it, but many large applications should.

like image 137
Joey Avatar answered Oct 12 '22 02:10

Joey