将每个检查存储在一个变量中,这样你只检查一次,然后重用该变量。
public bool Validate()
{
const string directoryErrorMessage = "Directory does not exist";
bool inPathExists = CheckPathExists(_settingsView.InPath);
bool outPathExists = CheckPathExists(_settingsView.OutPath);
bool processedPathExists = CheckPathExists(_settingsView.ProcessedPath);
if(!inPathExists) _settingsView.SetInPathError(directoryErrorMessage);
if(!outPathExists) _settingsView.SetOutPathError(directoryErrorMessage);
if(!processedPathExists) _settingsView.SetProcessedPathError(directoryErrorMessage);
return inPathExists &&
outPathExists &&
processedPathExists;
}
我不知道你是否有对_settingsView
类或不控制,但它可能是更好的让它处理验证本身。它可能会验证何时设置了路径,并设置适当的错误消息。然后在你的验证代码中,它只需要检查_settingsView对象的IsValid属性。
//to use the below class, your Validate method would change to
public bool Validate()
{
return _settingsView.IsValid;
}
internal class SettingsView
{
private const string DirectoryErrorMessage = "Directory does not exist";
private string _inPath;
private string _inPathError;
private bool _inPathValid;
private string _outPath;
private string _outPathError;
private bool _outPathValid;
private string _processedPath;
private string _processedPathError;
private bool _processedPathValid;
public string InPath
{
get
{
return _inPath;
}
set
{
_inPath = value;
_inPathValid = Directory.Exists(_inPath);
_inPathError = _inPathValid ? string.Empty : DirectoryErrorMessage;
}
}
public string InPathError
{
get
{
return _inPathError ?? string.Empty;
}
}
// Write similar code for Out and Processed paths
public bool IsValid
{
get
{
return _inPathValid && _outPathValid && _processedPathValid;
}
}
}
的多次调用CheckPathExists并没有真正的错误我,就像摆脱多个if语句。唯一改变的是路径字符串Ex:(CheckPathExists(_settingsView.xxxxxx))和错误消息方法SetxxxxError。我想知道是否有办法删除重复。 – Stevenr12