【发布时间】:2011-08-02 19:38:03
【问题描述】:
有一个类通过每个表有 1 个string[] 变量来定义各种表中的主键。例如:
static string[] my_table_foo_TablePrimaryKeys = new string[] { "primary_key1", "primary_key2" }
static string[] my_table_bar_TablePrimaryKeys = new string[] { "user_id", "customer_number" }
对于我们稍后添加第三个表并且我们想回到这个类来定义新的第三个表的主键的情况,我发现这有点混乱并且不太可扩展。因此,我将其重构为如下所示:
static Dictionary<string, string[]> tablePrimaryKeys = new Dictionary<string, string[]>()
{
{"my_table_foo", new string[] { "primary_key1", "primary_key2" }},
{"my_table_bar", new string[] { "user_id", "customer_number" }}
};
你们认为这是一个不错的重构更改吗?为什么?
此外,在我看来,引用主键的地方也更简洁一些。示例:
前一种情况:
DoStuffWithPrimaryKeys( my_table_foo_TablePrimaryKeys, "other stuff", 1000 );
在后一种情况下:
string[] keys = tablePrimaryKeys["my_table_foo"];
DoStuffWithPrimaryKeys( keys, "other stuff", 1000 );
如果有人还想提一下“可接受的重构”的原则是什么,以及如何知道什么是可接受的重构,什么是不可接受的,那就太好了,而且很有教育意义。
我正在使用 C# 和 .NET 3.5。
【问题讨论】:
-
如果
my_table_foo只存在于数据库中,这不是数据库问题吗?如果my_table_foo有一个匹配的 C# 类,你考虑过属性吗?
标签: c# refactoring