Which of the following alternatives would be preferred?
Include the error message within code wherever needed:
cout << "I am an error message!" <<endl;
exit(-1);
Define the error messages in a separate header file:
#include "ErrorMessages.h"
cout << ERRORMESSAGE_1 <<endl;
exit(-1);
Create a function that contains the error messages.
Also is it common to include unique error IDs as part of these messages?
It is all a matter of preference with both benefits and downfalls.
Hard-coding string literals at the site of the error may be harder to maintain but it also is easier to read in my honest opinion.
for example
cout << "You were unable to login. "
<< "Please check you're user name and password and try again"
<< endl;
shows intent a lot better than
cout << LOGIN_CREDENTIALS_ERROR << endl;
However, the plus sides of not hard-coding the message (both 2
and 3
):
//Foo.cpp:
cout << DIVIDE_BY_ZERO_ERROR << endl;
//Bar.cpp
cout << DIVIDE_BY_ZERO_ERROR << endl;
// If you want to change DIVIDE_BY_ZERO_ERROR text you only have to do it once
//ErrorMessages.h (Ops grammar needs correcting)
const std:string DIVIDE_BY_ZERO_ERROR = "Dont not divide by zero";
Also, if the error messages are subject to change:
// ErrorMessages.h
#ifdef LOCALIZATION_EN
const std:string FRIENDLY_ERROR = "Hello, you are doing something wrong";
#elseif LOCALIZATION_FR
const std:string FRIENDLY_ERROR = "Bonjour, ...";
...
OR
// ErrorMessages.h
#ifdef DEBUG
const std:string SOME_ERROR = "More detailed error information for developers"
#else
const std:string SOME_ERROR = "Human friendly error message"
#endif
It depends upon if you have localization requirements for your application. If you do, you want all your strings in one place, including error messages. If you don't have requirements like that, I prefer to put the messages inline (your first example). That way, if I want to find the code that's complaining, I can just grep the message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With