阅读配置值而不是使用魔术数字是否合适?

时间:2022-06-04 21:26:46

I have an idea that reading values from config files instead of using hard code values, but I'm not sure it is a good practice or not.

我有一个想法,从配置文件读取值而不是使用硬代码值,但我不确定这是一个好的做法。

First I created a utility class:

首先我创建了一个实用程序类:

public class ConfigValues
{ 
    public static int Read(string key, int defaultValue){....}
    public static string Read(string key, string defaultValue){....}
    public static bool Read(string key, bool defaultValue){....}
    ...
}

The Read function tries to read value for the given key. If the key doesnot exist or the value has bad format, it returns the default value. And I'm going to use this class like:

Read函数尝试读取给定键的值。如果密钥不存在或值格式错误,则返回默认值。而且我将使用这个类:

public class MyClass
{ 
    private int _age = ConfigValues.Read("Com.MyClass.Age", 0); 
    ...
}

So that, we can make almost all variables in the application customizable. Will it be a good practice? Please comment it for free.

这样,我们可以使应用程序中的几乎所有变量都可以自定义。这是一个好习惯吗?请免费评论。

4 个解决方案

#1


People who think you should make things configurable:

认为你应该让事情可配置的人:

People who think differently:

有不同想法的人:

The answer comes down to your requirements: why are you setting this value here?

答案取决于您的要求:为什么要在此处设置此值?

  • Is it something that different users will want set differently? => config file.
  • 这是不同的用户想要设置不同的东西吗? =>配置文件。

  • Is it just a default value to be changed later? => Hardcode it.
  • 它只是稍后要更改的默认值吗? =>硬编码。

  • Is it something which affects operational use of the program (i.e. default homepage for browser)? => Config file.
  • 是否会影响程序的操作使用(即浏览器的默认主页)? =>配置文件。

  • Is it something which might have complex impacts on various parts of the program? ... Answer depends on your userbase.
  • 是否可能对计划的各个部分产生复杂影响? ...答案取决于您的用户群。

Etc. It's not a simple yes-it's-good or no-it's-bad answer.

等等。这不是一个简单的是 - 它是好的或不是坏的答案。

#2


Configuration files are always a good idea.
Think of the INI files, for example.

配置文件总是一个好主意。例如,可以考虑INI文件。

It would be immensely useful to introduce a version numbering scheme in your config files.
So you know what values to expect in a file and when to look for defaults when these are not around. You might have hardcoded defaults to be used when the configurations are missing from the config file.

在配置文件中引入版本编号方案将非常有用。因此,您知道在文件中期望的值以及何时查找默认值时的值。当配置文件中缺少配置时,您可能会使用硬编码的默认值。

This gives you flexibility and fallback.

这为您提供了灵活性和后备。

Also decide if you will be updating the file from your application.
If so, you need to be sure it can manage the format of the file.
You might want to restrict the format beforehand to make life simpler.

还要决定是否要从应用程序更新文件。如果是这样,您需要确保它可以管理文件的格式。您可能希望事先限制格式以使生活更简单。

You could have CSV files or "name=value" INI style files.
Keep it simple for your code and the user who will edit them.

您可以拥有CSV文件或“name = value”INI样式文件。为您的代码和将要编辑它们的用户保持简单。

#3


Configuration file also allow you to update the values without doing another build to change a single value. This can be useful to have one build for all environments, with different configuration values (log levels, user names, etc.). Also, if you cache the values and periodically update from the file, it allows you to make changes on the fly while the application is still running. This may be overkill in some situations, but it can be very helpful in debugging certain issues.

配置文件还允许您更新值而无需执行其他构建来更改单个值。这对于具有不同配置值(日志级别,用户名等)的所有环境具有一个构建是有用的。此外,如果您缓存值并定期从文件更新,它允许您在应用程序仍在运行时动态进行更改。在某些情况下这可能有点过头了,但它在调试某些问题时非常有用。

#4


Do:

  • Create a new C# project
  • 创建一个新的C#项目

  • Menu->Project->[Project name] Properties
  • 菜单 - >项目 - > [项目名称]属性

  • Open Settings pane
  • 打开“设置”窗格

  • Create your settings (it's strongly typed)
  • 创建您的设置(强类型)

Usage:

class Program
{
    static void Main(string[] args)
    {
        int setting1 = Properties.Settings.Default.Setting1;
        Properties.Settings.Default.Setting1 = 43534;            
        Proerties.Settings.Default.Save();
    }
}

Note that Properties is a namespace and you can import it so you can use Settings.Default.Setting1.

请注意,Properties是一个命名空间,您可以将其导入,以便使用Settings.Default.Setting1。

Here is a more detailed link.

这是一个更详细的链接。

If you use a windows forms application, you could change the Program.cs file to save all the changed settings when leaving application:

如果使用Windows窗体应用程序,则可以在离开应用程序时更改Program.cs文件以保存所有更改的设置:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Add this line
        Application.ApplicationExit +=
                            new EventHandler(Application_ApplicationExit);
        Application.Run(new Form1());
    }

    //and this method:
    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        Properties.Settings.Default.Save();
    }
}

#1


People who think you should make things configurable:

认为你应该让事情可配置的人:

People who think differently:

有不同想法的人:

The answer comes down to your requirements: why are you setting this value here?

答案取决于您的要求:为什么要在此处设置此值?

  • Is it something that different users will want set differently? => config file.
  • 这是不同的用户想要设置不同的东西吗? =>配置文件。

  • Is it just a default value to be changed later? => Hardcode it.
  • 它只是稍后要更改的默认值吗? =>硬编码。

  • Is it something which affects operational use of the program (i.e. default homepage for browser)? => Config file.
  • 是否会影响程序的操作使用(即浏览器的默认主页)? =>配置文件。

  • Is it something which might have complex impacts on various parts of the program? ... Answer depends on your userbase.
  • 是否可能对计划的各个部分产生复杂影响? ...答案取决于您的用户群。

Etc. It's not a simple yes-it's-good or no-it's-bad answer.

等等。这不是一个简单的是 - 它是好的或不是坏的答案。

#2


Configuration files are always a good idea.
Think of the INI files, for example.

配置文件总是一个好主意。例如,可以考虑INI文件。

It would be immensely useful to introduce a version numbering scheme in your config files.
So you know what values to expect in a file and when to look for defaults when these are not around. You might have hardcoded defaults to be used when the configurations are missing from the config file.

在配置文件中引入版本编号方案将非常有用。因此,您知道在文件中期望的值以及何时查找默认值时的值。当配置文件中缺少配置时,您可能会使用硬编码的默认值。

This gives you flexibility and fallback.

这为您提供了灵活性和后备。

Also decide if you will be updating the file from your application.
If so, you need to be sure it can manage the format of the file.
You might want to restrict the format beforehand to make life simpler.

还要决定是否要从应用程序更新文件。如果是这样,您需要确保它可以管理文件的格式。您可能希望事先限制格式以使生活更简单。

You could have CSV files or "name=value" INI style files.
Keep it simple for your code and the user who will edit them.

您可以拥有CSV文件或“name = value”INI样式文件。为您的代码和将要编辑它们的用户保持简单。

#3


Configuration file also allow you to update the values without doing another build to change a single value. This can be useful to have one build for all environments, with different configuration values (log levels, user names, etc.). Also, if you cache the values and periodically update from the file, it allows you to make changes on the fly while the application is still running. This may be overkill in some situations, but it can be very helpful in debugging certain issues.

配置文件还允许您更新值而无需执行其他构建来更改单个值。这对于具有不同配置值(日志级别,用户名等)的所有环境具有一个构建是有用的。此外,如果您缓存值并定期从文件更新,它允许您在应用程序仍在运行时动态进行更改。在某些情况下这可能有点过头了,但它在调试某些问题时非常有用。

#4


Do:

  • Create a new C# project
  • 创建一个新的C#项目

  • Menu->Project->[Project name] Properties
  • 菜单 - >项目 - > [项目名称]属性

  • Open Settings pane
  • 打开“设置”窗格

  • Create your settings (it's strongly typed)
  • 创建您的设置(强类型)

Usage:

class Program
{
    static void Main(string[] args)
    {
        int setting1 = Properties.Settings.Default.Setting1;
        Properties.Settings.Default.Setting1 = 43534;            
        Proerties.Settings.Default.Save();
    }
}

Note that Properties is a namespace and you can import it so you can use Settings.Default.Setting1.

请注意,Properties是一个命名空间,您可以将其导入,以便使用Settings.Default.Setting1。

Here is a more detailed link.

这是一个更详细的链接。

If you use a windows forms application, you could change the Program.cs file to save all the changed settings when leaving application:

如果使用Windows窗体应用程序,则可以在离开应用程序时更改Program.cs文件以保存所有更改的设置:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        //Add this line
        Application.ApplicationExit +=
                            new EventHandler(Application_ApplicationExit);
        Application.Run(new Form1());
    }

    //and this method:
    static void Application_ApplicationExit(object sender, EventArgs e)
    {
        Properties.Settings.Default.Save();
    }
}