泛化布尔函数以获得更优雅的代码

Generalising Boolean Functions for more elegant code

本文关键字:代码 布尔 函数 泛化      更新时间:2023-10-16

我一直认为,如果你正在复制和粘贴代码,那么有一个更优雅的解决方案。我目前正在C++中实现一个字符串后缀trie,并且有两个几乎相同的函数,它们仅在返回语句上有所不同。

第一个函数检查

子字符串是否存在,第二个函数检查它是否是后缀(所有字符串都有字符#添加到末尾)。

子字符串(字符串 S)

bool Trie::substring(string S){
    Node* currentNode = &nodes[0];                          //root
    for(unsigned int i = 0; i < S.length(); i++){
        int edgeIndex = currentNode->childLoc(S.at(i));
        if(edgeIndex == -1)
            return false;
        else currentNode = currentNode->getEdge(edgeIndex)->getTo();
    }
    return true;
}

后缀(字符串 S)

bool Trie::suffix(string S){
    Node* currentNode = &nodes[0];                          //root
    for(unsigned int i = 0; i < S.length(); i++){
        int edgeIndex = currentNode->childLoc(S.at(i));
        if(edgeIndex == -1)
            return false;
        else currentNode = currentNode->getEdge(edgeIndex)->getTo();
    }
    return (currentNode->childLoc('#') == -1)? false : true;    //this will be the index of the terminating character (if it exists), or -1.
}

如何才能更优雅地概括逻辑?也许使用模板?

在这种情况下,我个人所做的是将通用代码移动到函数中,我从多个地方调用该函数,我需要的地方,说通用功能。考虑一下:

Node* Trie::getCurrentNode (string S){
    Node* currentNode = &nodes[0];  
    for(unsigned int i = 0; i < S.length(); i++){
        int edgeIndex = currentNode->childLoc(S.at(i));
        if(edgeIndex == -1)
            return nullptr;
        else currentNode = currentNode->getEdge(edgeIndex)->getTo();
    }
    return currentNode;
}

然后,在所有情况下,在您需要的地方使用它:

bool Trie::substring(string S){
    return getCurrentNode (S) != nullptr;
}
bool Trie::suffix(string S){
    Node* currentNode = getCurrentNode(S);
    return currentNode != nullptr && currentNode->childLoc('#') != -1;
    // I decided to simplify the return statement in a way François Andrieux suggested, in the comments. It makes your code more readable.
}