Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 861
Ofek Agmon Avatar asked May 04 '16 18:05

Ofek Agmon


People also ask

Should a constants class be static?

Yes the class should be static .

Where should I store constants Java?

Even if a constant is used throughout the code but always in relation to one class, it should clearly be part of that class (e.g. BorderLayout. CENTER).

Where do you put constants?

You can also use static const in header for small constants, if constant variable for some reason must have internal linkage. So to answer your question, for global constant variable, define it in source, and declare it as extern const in header. @Akay For integer error constants enum is usually the best option.

Can strings be constant?

A String Literal, also known as a string constant or constant string, is a string of characters enclosed in double quotes, such as "To err is human - To really foul things up requires a computer." String literals are stored in C as an array of chars, terminted by a null byte.


Video Answer


3 Answers

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.

like image 76
Win Avatar answered Oct 17 '22 03:10

Win


I usually make a distinction based on the intended audience for the message. As such, I break them into two categories.
Regardless of the category, I avoid writing the same code more than once (e.g. message strings).

Developer Messages

  • Messages displayed in unit tests, messages displayed only during debugging, or messages logged to super-detailed diagnostic files
  • Developer messages require no localization and should be written in the language of the development house.
    For example, if the development company is located in Moscow, then there's a strong argument to write developer messages in Russian.
    In practice, a lot of developers choose English.
  • Implementation options are multiple. I typically keep it simple, using fields in a static class. Note that you could have a message class for each type that will display messages, or you could have a central message class where you group multiple classes. You could have nested message groups. You could also add other types of constants for use in your code... As I mentioned, options and preferences abound.

    public static class FeatureMessages
    {
        #region Public Fields
    
        public const string ApiAccessError = 
            @"Error accessing api - check internet connection/api address";
        public const string SelectedClassFormatString = 
            @"Hello dear user – the selected class name is {0}";
    
        #endregion
    }
    

User Messages

  • Messages displayed to end users. For example, installation prompts, in the user GUI menus, on a user warning message boxes, etc.
  • These messages should be localized.
  • Implementation is simple, and will require at least a default language resource file. There are lots of resources out there that can show you how to do this, you can see a simple explanation here
like image 35
Gustavo Mori Avatar answered Oct 17 '22 03:10

Gustavo Mori


I would generally recommend using a resource file (created from your project settings). You may want to provide some kind of wrapper if you want to make this code more testable.

like image 6
drz Avatar answered Oct 17 '22 02:10

drz