Avoid Hardcoded Literal Strings

Avoid Hardcoded Literal Strings

Hardcoded literal strings can become a serious maintenance problem. Suppose you have numerous message boxes in your application that display a hardcoded text message and you want to change that message. You have to chase every occurrence of the message box in your source file. A similar problem will arise when you internationalize or localize an existing application. To avoid this problem in the first place, use constants or string tables instead of hardcoded strings. This way, you will have to change a message only in one place:

 // file messages.hconst char msg1[] = "hello";const char msg2[] = "goodbye";// file app.cppvoid f(){ messagebox(INFO, msg1);}int main(){ messagebox(INFO, msg1);}

To create a French version of this program, all you have to do is replace the constant strings in messages.h and recompile:

 const char msg1[] = "bonjour";const char msg2[] = "au revoir";

No additional changes in the source files are needed.


Share the Post: