我有一個功能AppendLastSlashIfNotExist
。
今天,我決定再進行一次功能AppendLastBackSlashIfNotExist
如何刪除這個簡單代碼中的重複?
wstring AppendLastSlashIfNotExist(__in const wstring& path)
{
if (path == L"/")
{
return path;
}
if (path.size() == 0 || path[path.size() - 1] != L'/')
{
return path + L"/";
}
return path;
}
wstring AppendLastBackSlashIfNotExist(__in const wstring& path)
{
if (path == L"\\")
{
return path;
}
if (path.size() == 0 || path[path.size() - 1] != L'\\')
{
return path + L"\\";
}
return path;
}
是的,它吮吸。只有斜槓 - >BackSlash是變化。我想刪除重複。
wstring AppendLastSlashIfNotExist(__in const wstring& path, bool backSlash)
{
if (path == (backSlash ? L"\\" : L"/"))
{
return path;
}
if (path.size() == 0 || path[path.size() - 1] != (backSlash ? L'\\' : L'/'))
{
return path + (backSlash ? L"\\" : L"/");
}
return path;
}
我整合了它們。重複刪除。但有一個額外的參數。我仍然感到不舒服。 是否有其他方法可以消除重複?例如,使用高階函數。
請任何想法。
我想你應該合併Path類而不是使用這些函數。在你的班級路徑中,你會關心你的路徑字符串的有效性。使用OO概念。 – AlexTheo 2012-01-04 09:23:55
指示'bool backSlash = false'的默認值。 – atoMerz 2012-01-04 09:32:07