.Net - 避免魔术字符串的策略
在工作代码中,我们有很多使用魔术字符串的情况,如下面的代码片段:
if (user.HasRight("Profile.View")) {...}
因此,有很多地方我们传递字符串作为参数来查看用户是否具有特定的权限。我不喜欢这样,因为这会产生很多神奇的字符串。
更好的方法是什么?
枚举、常量、类?
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?
Enum, Constant, class ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在这种特定情况下,请使用枚举。不会有魔术字符串,如果枚举发生变化(以破坏魔术字符串解决方案的方式),应用程序将不再编译。
然后你可以简单地拥有:
你也可以使用一个类,但是当涉及到更复杂的场景时你就会限制自己。例如,将枚举简单更改为:
将允许您使用按位运算符来获得更复杂的权限(例如,用户需要创建或删除的情况):
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.
Then you can simply have:
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:
Would allow you to use bitwise operators for more complex permissions (for example, a situation where a user needs either Create or Delete):
这在 .NET 框架中也很常见。示例包括 System.Windows.DataFormats 和 System.Net.WebRequestMethods.Http。您需要只读品种:
This is common enough in the .NET framework as well. Examples are System.Windows.DataFormats and System.Net.WebRequestMethods.Http. You'd want the readonly variety:
扩展方法!将它们放在同一个地方以跟踪所有魔法弦。
然后你可以:
Extension methods! Keep them in the same place to keep track of all magic strings.
Then you can:
创建一个对这些属性进行强类型化的类,例如
这会将您的“魔术字符串”保留在代码中的一个位置。枚举也可以工作,但在我看来可读性较差。
注意:我的示例旨在充当登录用户的属性代理,即静态类。如果您想要一些可以处理更直接的数据(例如,用户列表)的东西,这种类型的类需要是非静态的,并在每个用户帐户的基础上实例化。
Create a class which strongly-types those properties, like
This will keep your "magic strings" in one place within your code. An enum will also work, but isn't as readable in my opinion.
Note: my example is intended to act as a property proxy for the logged in user, thus the static class. If you wanted something that would work on more immediate data (say, a list of users), this type of class would need to be non-static and instantiated on per-user-account basis.
您可以在 C# 中执行常量字符串。
您可以像这样定义标头中的所有字符串:
不确定这是否是“最佳”方式,但它肯定比在代码中包含魔法值更好。
You can do constant strings in C#.
You could define all of the strings in a header like this:
Not sure if this is the "best" way, but its certainly better than having magic values in the code.
我赞同“Justin Niessner”所展示的方式。但在某些情况下,我宁愿编写以下代码结构。
你可以把它当作
I second the way shown by "Justin Niessner". But in some cases I would rather prefer writing following construct of code.
and you can consume it as