0

我正在尝试验证字符串的有效性,以确保它是我可以传递给终端的合法命令。如果字符串通过测试,我返回 True。否则,我返回 False 和一条错误消息。

我的代码非常难看,有很多嵌套的 if 语句 - 我该如何改进它?

task = task.split()
if len(task) > 1: 
    if task[0] == 'svn':
        if task[1] in ALLOWED:
            if len(task[2:]) == ALLOWED[task[1]]:
                return True, task, None
            else:
                return False, "Incorrect number of arguments."
        else:
            return False, "Not a legal command."    
    else:
        return False, "Not a subversion command."
else:
    return False, "Invalid input"
4

2 回答 2

5

而不是肯定检查和嵌套 if 语句:

if a:
    if b:
        if c:
            foo()
        else:
            # error 3
     else:
         # error 2
else:
    # error 1

除非一切正常,否则您可以反转逻辑并退出:

if not a:
    # raise an exception

if not b:
    # raise an exception

if not c:
    # raise an exception

# If we get here, everything is OK.
foo()

这样可以更容易地查看哪个错误消息与哪个条件匹配。

于 2012-07-30T22:57:16.573 回答
2

以下是如何针对您的案例具体实施 Mark Byer 的答案的示例:

task = task.split()
if len(task) < 2:
    return False, "Invalid input"
if task[0] != 'svn':
    return False, "Not a subversion command."
if task[1] not in ALLOWED:
    return False, "Not a legal command."    
if len(task[2:]) != ALLOWED[task[1]]:
    return False, "Incorrect number of arguments."  
return True, task, None
于 2012-07-30T23:00:30.253 回答