枚举上的属性太多了?

时间:2012-11-14 12:45:26

标签: oop enums

我的系统目前在不同的环境中运行。

我的系统上有一个环境枚举,类似这样的

public enum Environment {

    [UsePayPal(false)]
    [ServerInstallDir("InstallPathOnServer")]
    [IntegrationSystemURI("localhost/someFakeURI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("DEV")]
    [UseCache(false)]
    [AnotherSystemURI("localhost/anotherFakeURI")]
    Development = 0,

    [UsePayPal(false)]
    [ServerInstallDir("InstallPathOnBUILDServer")]
    [IntegrationSystemURI("build-server/someFakeURI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("QA")]
    [UseCache(false)]
    [AnotherSystemURI("build-server/anotherFakeURI")]
    QA = 1,

    [UsePayPal(true)]
    [ServerInstallDir("InstallPathOnServer")]
    [IntegrationSystemURI("someservice.com/URI")]
    [UpdateSomeInfo(true)]
    [QueuePrefix("PRD")]
    [UseCache(true)]
    [AnotherSystemURI("anotherservice/URI")]
    Production = 2,
}

我这样工作,因为我不喜欢像

这样的代码
if(CURRENT_ENVIRONMENT == Environment.QA || CURRENT_ENVIRONMENT == Environment.DEV)
    EnableCache()

if(CURRENT_ENVIRONMENT == Environment.QA || CURRENT_ENVIRONMENT == Environment.DEV){
    DoSomeStuff();
}

因为我认为这会在整个系统中分散我的逻辑,而不是在一个点上。

如果有一天我添加了另一个测试环境,我不需要遍历我的代码,看看我是否像开发,质量保证或生产环境一样工作。

好的,但是,有了所有的配置,我可能会在我的Enum上得到太多的maby属性,让我们说,在3年内每个枚举值将有15~20个属性,这看起来很奇怪。

你们觉得怎么样?你通常如何处理这种情况?它真的有太多的属性,或者没关系?

1 个答案:

答案 0 :(得分:3)

创建一个Environment类,其中包含private构造函数和描述环境所需的多个属性,并将static readonly个实例公开为公共属性。您还可以拥有指向其中一个实例的Environment.Current属性。

示例代码:

sealed class Environment
{
    // The current environment is going to be one of these -- 1:1 mapping to enum values
    // You might also make these properties if there's fine print pointing towards that
    public static readonly Environment TestEnvironment;
    public static readonly Environment ProductionEnvironment;

    // Access the environment through this
    public static Environment Current { get; set; }

    static Environment()
    {
        TestEnvironment = new Environment {
            UsePayPal = false,
            ServerInstallDir = "/test"
        };
        ProductionEnvironment = new Environment { 
            UsePayPal = true, 
            ServerInstallDir = "/prod"
        };
    }

    // Environment propeties here:
    public bool UsePayPal { get; private set; }
    public string ServerInstallDir { get; private set; }

    // We don't want anyone to create "unauthorized" instances of Environment
    private Environment() {}
}

使用它像:

Environment.Current = Environment.TestEnvironment;

// later on...
Console.WriteLine(Environment.Current.ServerInstallDir);