从验证方法中删除重复
本文关键字:删除 验证 方法 | 更新日期: 2023-09-27 18:10:37
在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);
}
为每个路径调用CheckPathExists()两次,尝试只调用一次,将结果保存为布尔值,然后使用布尔变量值
在class中创建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;
}
将每个检查存储在一个变量中,这样您只检查一次,然后重用该变量。
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;
}
}
}