在validate方法中删除重复的好方法是什么?
public bool Validate()
{
string directoryErrorMessage = "Directory does not exist";
if(!CheckPathExists(_settingsView.InPath)) _settingsView.SetInPathError(directoryErrorMessage);
if(!CheckPathExists(_settingsView.OutPath)) _settingsView.SetOutPathError(directoryErrorMessage);
if(!CheckPathExists(_settingsView.ProcessedPath)) _settingsView.SetProcessedPathError(directoryErrorMessage);
return CheckPathExists(_settingsView.InPath) &&
CheckPathExists(_settingsView.OutPath) &&
CheckPathExists(_settingsView.ProcessedPath);
}
private bool CheckPathExists(string path)
{
return Directory.Exists(path);
}
答案 0 :(得分:0)
您为每个路径调用两次CheckPathExists(),尝试只调用一次,将结果保存为布尔值,然后使用布尔变量值。
答案 1 :(得分:0)
将每个检查存储在变量中,这样您只需检查一次,然后重复使用该变量。
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;
}
}
}
答案 2 :(得分:0)
在课堂上创建3个方法:
public bool Validate()
{
return CheckInPath() &CheckOutPath()&CheckProcessedPath();
}
public bool CheckInPath()
{
if(!CheckPathExists(_settingsView.InPath)) {
_settingsView.SetInPathError(directoryErrorMessage);
return false;
}
return true;
}
public bool CheckOutPath(string path)
{
if(!CheckPathExists(_settingsView.InPath)) {
_settingsView.SetOutPathError(directoryErrorMessage);
return false;
}
return true;
}
public bool CheckProcessedPath(string path)
{
if(!CheckPathExists(_settingsView.ProcessedPath)) {
_settingsView.SetProcessedPathError(directoryErrorMessage);
return false;
}
return true;
}