將每個檢查存儲在一個變量中,這樣你只檢查一次,然後重用該變量。
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