Need string manifest to avoid magic strings in webapi c# application

363 Views Asked by At

I have a c# webapi application which has magic strings and numbers everywhere. I am asked to change this by having a string manifest or a bundle which holds these strings in one place and refer them. I don’t want to use Enum. I don’t know what is string manifest or bundle.

Can someone please give me an idea on how to do this with an example. Basically I need to avoid the hard coding throughout the application and use an external configuration for these strings so that whenever these string values change, we don't have to compile and deploy the .NET application.

Idea is to have all the expected responses in some kind of bundle or string manifest and refer to that rather than have magic numbers and strings everywhere.

I need to remove the magic case numbers and FreeText and instead configure those values in a single place and refer them without having to deploy the application again.

switch (ReasonCode) 
{ 
    case 0: 
        FreeText = "Passed. Please proceed"; 
        break;
    case 1: 
        FreeText = "Fail"; 
        break;
}
1

There are 1 best solutions below

0
Orace On

Enum are the preferred way to store magic constant when they are integers.

For string constant, the simple way to do it is one or more static class that expose the code:

public static class ApiCodes
{
  public int RootUserCode { get; } = 42;
  public string DeleteActionCode { get; } = "REM";
  // ..
}

A magic code value change can be done in a single place, and the code is pretty readable:

public void DoAction(string actionCode)
{
  if (actionCode == ApiCodes.DeleteActionCode)
  {
    ..
  }
}

Edit:

With singletons and a static class at root level, you can also have a hierarchy:

public static class ApiCodes
{
    public static ActionCodes ActionCodes { get; } = ActionCodes.Instance;
}

public class ActionCodes
{
    public static ActionCodes Instance { get; } = new ActionCodes();

    // Singleton: private constructor
    private ActionCodes()
    {
    }

    public string Add { get; } = "ADD";
    public string Delete { get; } = "REM";
}

And use it like that:

public void DoAction(string actionCode)
{
  if (actionCode == ApiCodes.ActionCodes.Delete)
  {
    ..
  }
}