如果我知道一个方法必须执行一定次数的操作,例如检索数据,我应该编写代码来专门执行所需的次数,还是我的代码应该能够预测以后的更改?例如,假设我被告知要编写一个从字典中检索 2 个值的方法(在这里我称之为设置)并使用提供的已知键返回它们
public Dictionary<string, string> GetSettings()
{
const string keyA = "address"; //I understand 'magic strings' are bad, bear with me
const string keyB = "time"
Dictionary<string, string> retrievedSettings = new Dictionary<string,string>();
//should I add the keys to a list and then iterate through the list?
List<string> listOfKeys = new List<string>(){keyA, keyB};
foreach( string key in listOfKeys)
{
if(Settings.ContainsKey(key)
{
string value = Setting[key];
retrieveSettings.Add(key, value);
}
}
//or should I just get the two values directly from the dictionary like so
if(Settings.ContainsKey(keyA)
{
retrievedSettings.Add(keyA , Setting[keyA]);
}
if(Settings.Contains(keyB)
{
retrievedSettings.Add(keyB , Setting[keyB]);
}
return retrievedSettings
}
我问的原因是代码重复总是一件坏事,即 DRY,但同时,更有经验的程序员告诉我,如果只需要执行操作,则无需编写逻辑来预期更大的循环已知次数