【发布时间】:2012-01-04 09:14:30
【问题描述】:
有一个函数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;
}
是的,很糟糕。只有 Slash -> 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 概念。
-
表示
bool backSlash=false的默认值。
标签: c++ design-patterns refactoring code-duplication