a有一个外部dll,它根据提供的itemID返回用户信息数组。一个简单的代码,可能是:
private string userName;
private int userAge;
const string NAME = "NAME";
const string AGE = "AGE";
string[] arrID = { NAME, AGE }; //IDs to get name and age, to get surname please add "SURNAME" to the array
User[] users;
string[] results; //OK - item found, Unknown - item id not found
////////read from external dll////////
databaseAccessor.GetUsers(arrID, out users, out results);
//////////////////////////////////////
int itemNameIndex = Array.IndexOf(arrID, NAME);
int itemAgeIndex = Array.IndexOf(arrID, AGE);
if(results[itemNameIndex] == "OK")
{
userName = users[itemNameIndex].Name;
}
if(results[itemAgeIndex] == "OK")
{
userAge = users[itemAgeIndex].Age;
}
我不喜欢这段代码,因为在尝试获取新用户时,必须添加一个新的if子句"功能"例如高度。有一点是无法改变的是外部dll databaseAccessor.GetUsers(arrID, out users, out results);
重构它以避免添加新ifs的最佳方法是什么?
答案 0 :(得分:0)
我猜你可以为外部调用创建一个包装类来解释那里的结果。然后,您可以确保仅返回有效的用户实体,这些实体将是单独的用户实体类的实例以及名称和年龄等属性。这将使我看起来更清洁(如果需要更容易更换外部DLL)。类似的东西:
IEnumerable<UserEntity> users = UserManager.Get();
然后,只需实现访问UserManager.Get
中用户所需的所有代码。您当然可以创建一些私有方法来访问数组中的信息。与TryGetValue类似,它检查results[itemNameIndex] == "OK"
然后返回值。
所以将它包装起来并使代码检索更通用的代码将是我的建议。