It's a simple problem that got me confused.
I have two classes and a dictionary (simplified for the sake of the example):
class Result {
public string Description;
}
class Error {
public int ErrorCode;
}
Dictionary<int, string> errorCodeToMessage = new Dictionary<int, string> {
{ 0, "Item not found" },
{ 1, "Connection error" }
}
In the code base I inherited I see this line very often:
Result result = new Result {
Description = errorCodeToMessage[error.ErrorCode];
}
I do not want the dictionary to be used all over, I want this logic to be encapsulated in either the Result
object or the Error
object.
I thought about creating a new constructor in the Result
object that will accept an ErrorCode and doing the logic there. But I'm not sure this is the best way.
How would you do it?
In .NET you should use ResourceManager for this. This way you'll have all possible messages encapsulated in a place where they belong.
In essence there is nothing wrong in using an entity which provides messages all over the application - because it's a good example of a Singleton. You could however partition the messages into different containers. A simple example:
enum ErrorCode
{
SomethingIsWrong,
AnotherThingIsWrong,
UserIsAnIdiot
}
In a ErrorCodes.resx
file:
<data name="SomethingIsWrong" xml:space="preserve">
<value>Something is wrong. Sorry!</value>
</data>
<data name="AnotherThingIsWrong" xml:space="preserve">
<value>Another thing is wrong. Sorry!</value>
</data>
<data name="UserIsAnIdiot" xml:space="preserve">
<value>You're an idiot! '{0:dd-MMM-yyyy}' is not a future date!</value>
</data>
And you can use this like this:
public void GetErrorMessage(ErrorCode errorCode)
{
//ErrorCodes is a class accompanying the ErrorCodes.resx file
var rm = new ResourceManager(typeof(ErrorCodes));
//or with a CultureInfo instance if you want localized messages
return rm.GetString(errorCode.ToString());
}
This GetErrorMessage
method will be in some kind of a singleton, or a static class used all over your application. You can separate message types between each other puting them into different resx files, which will be enclosed by different classes, generated by VS.