Search code examples
c#stringoopdesign-patternsinterface

Best practice for constant string for implementations to use


Say I have an interface:

public interface IFeature
{
    Task execFeature();
}

and two implementations:

public class FirstFeature : IFeature
{
    private IWebApi webApi;
    public FirstFeature(IWebApi webApi)
    {
        this.webApi = webApi;
    }

    public async Task execFeature()
    {
        string response = await webApi.getClassName();
        IResult result;
        if(response==null)
            result = new TextResult("Error accessing api - check internet connection/api address");
        else
            result = new TextResult("Hello dear user – the selected class name is " + response);
        result.display();
    }
}

public class SecondFeature : IFeature
{
    private IWebApi webApi;
    public SecondFeature(IWebApi webApi)
    {
        this.webApi = webApi;
    }

    public async Task execFeature()
    {
        List<string> classNames = new List<string>();
        var classNameTasks = Enumerable.Range(1, 3).Select(i => webApi.getClassName()).ToArray();
        classNames.AddRange((await Task.WhenAll(classNameTasks)));
        IResult result;
        if (classNames[0] == null)
            result = new TextResult("Error accessing api - check internet connection/api address");
        else 
            result = new TextResult("Hello dear user – we’ve selected three new class names for you, and they are " + classNames[0] + ", " + classNames[1] + ", and " + classNames[2]);
        result.display();
    }
}

As you can see, in both implementations I had to do the result = new TextResult("Error accessing api - check internet connection/api address"); line to report the error.

What is the best practice in OOP/Good Design to have a constant error_string that I can access in all of my implementations?

the way it is right now, code is duplicated.


Solution

  • I don't think there is a best practice. It is just a matter of preference.

    I store constants inside static classes.

    public static class Constants
    {
       public static class Messages
       {
          public const string Error = "Error accessing api...";
          public const string Hello = "Hello ...";
       }
    }
    

    Usage

    var result = new TextResult(Constants.Messages.Error);
    

    FYI: Some developers prefer Enum.