2012-07-30 38 views
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" 
+1

如果「到終端」你真的是「以殼」,這是一個壞主意。如果你有安全考慮,你仍然容易受到注入炮彈的影響。確保你沒有調用shell,並使用'subprocess'模塊。而不是返回一個布爾,你可能想引發一個異常。 – Julian 2012-07-30 22:54:08

回答

5

而不是積極的檢查和嵌套的if語句:

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

可以逆轉的邏輯和保釋出來,除非一切都OK了:

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() 

這使得它更容易看到哪些錯誤消息與哪個條件匹配。

+0

如果沒有問題,我會附上我的答案給你。由於我的基本上就是你的例子。 – 2012-07-30 23:01:11

+1

@JoelCornett:你可以離開你的。我只是+1了。你甚至可能會接受... – 2012-07-30 23:03:57

+0

欣賞它。順便說一句,在我的代碼中,我使用'if ... elif ... elif ... else',而如果你做'if ... if ... if'。作爲一個風格問題,是否有理由相對於另一方偏好? – 2012-07-30 23:18:32

2

下面是如何馬克·拜爾的回答能爲你的情況來實施具體的例子:

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