净 - 策略以避免魔术字符串字符串、魔术、策略、以避免

2023-09-03 16:18:18 作者:滾

在code在工作中,我们有一个神奇的字符串,如以下code段很多用途:

In code at work, we have many uses of magic strings like the following code snippet:

if (user.HasRight("Profile.View")) {...}

因此​​,有在那里我们传递字符串作为参数来查看用户是否具有特定的权利许多地方。我不喜欢这样,因为这会产生很多神奇的字符串。

So there are many places where we pass a string as a parameter to see if the user has a specific right. I don't like that because that generates a lot of magic strings.

什么是做一个更好的办法?

What would be a better way of doing it?

枚举,常量,类?

推荐答案

在特定情况下,使用一个枚举。不会有神奇的字符串,如果枚举的变化(在某种程度上会破坏魔术字符串的解决方案),应用程序将不再进行编译。

In that specific case, use an Enum. There will be no magic strings and if the Enum changes (in a way that would break the magic strings solution), the app will no longer compile.

public enum ProfilePermissions
{
    View,
    Create,
    Edit,
    Delete
}

然后,你可以简单地有:

Then you can simply have:

if(user.HasRight(ProfilePermissions.View)) { }

您也可以使用一类,但你限制自己,当涉及到更复杂的情况。例如,枚举的一个简单的改变是这样的:

You could also use a class, but then you limit yourself when it comes to more complex scenarios. For instance, a simple change of the Enumeration to something like:

public enum ProfilePermissions
{
    View = 1,
    Create = 2,
    Edit = 4,
    Delete = 8
}

(其中用户需要创建或删除例如,一种情况)将允许您使用按位运算符用于更复杂的权限:

Would allow you to use bitwise operators for more complex permissions (for example, a situation where a user needs either Create or Delete):

if(user.HasRight(ProfilePermissions.Create | ProfilePermissions.Delete));