Search code examples
c++design-patternsrefactoringcode-duplication

How to remove duplication in this simple code?


There is a function AppendLastSlashIfNotExist I made.
Today, I've decided to make another function 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;
}

Yes, it sucks. Only Slash -> BackSlash is the change. I wanted to remove duplications.

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;
}

I integrated them. Duplication removed. But an additional parameter came. I still feel uncomfortable. Isn't there other ways to remove duplication? For example, using by high-order function.
Any idea please.


Solution

  • Instead of passing a boolean to indicate the slash type you could just pass the slash character that is required, and possibly have a default for the slash character:

    wstring AppendLastSlashIfNotExist(__in const wstring& path,
                                      wchar_t slash = L'\\')
    {
        // This is superfluous and is handled in next if condition.
        /*if (1 == path.length() && path[0] == slash)
        {
            return path;
        }*/
    
        if (path.size() == 0 || path[path.size() - 1] != slash)
        {
            return path + slash;
        }
        return path;
    }
    
    std::wstring s(L"test");
    std::wcout << AppendLastSlashIfNotExist(s) << "\n";
    std::wcout << AppendLastSlashIfNotExist(s, L'/') << "\n";