我有一个功能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