2016-02-17 45 views
1

是否有可能擺脫這個代碼中無用的ok變量?切換「非其他」情況?

cond1 = true 
cond2 = true 
cond3 = true 

switch 
    when !cond1 
    console.log "cond1 failed" 
    when !cond2 
    console.log "cond2 failed" 
    when !cond3 
    console.log "cond3 failed" 
    else 
    ok = true 

if !ok then process.exit(1) 

console.log "good" 

回答

1

您可以複製狀態檢查的缺點更改您的代碼

cond1 = true 
cond2 = true 
cond3 = true 

switch 
    when !cond1 
    console.log "cond1 failed" 
    when !cond2 
    console.log "cond2 failed" 
    when !cond3 
    console.log "cond3 failed" 

process.exit(1) if !(cond1 && cond2 && cond3) 

console.log "good" 

我想你想顯示所有未滿足的條件(因爲你在switch語句後放了process.exit調用)。如果是這樣,你的代碼有問題,它只會顯示第一個未滿足的條件。所以,我只想用if語句

cond1 = false 
cond2 = false 
cond3 = true 

if !cond1 
    console.log "cond1 failed" 
if !cond2 
    console.log "cond2 failed" 
if !cond3 
    console.log "cond3 failed" 

process.exit(1) if !(cond1 && cond2 && cond3) 

console.log "good" 

遍佈所有你需要決定是否你的條件或一個設置和可變的檢查雙重檢查與您的代碼的可讀性比較昂貴。

我會給可讀性更高的優先級,如果有性能或內存的問題不是真的處理的使用是這樣的:

cond1 = false 
cond2 = false 
cond3 = true 

error={"success":true,"msg":"good"} 

addError=(msg)-> 
    error.msg="" if error.success 
    error.success=false 
    error.msg+=msg+"\n" 

checkForErrors=(e)-> 
    console.log e.msg   
    if !e.success 
    process.exit(1) 

addError "cond1 failed" if !cond1 
addError "cond2 failed" if !cond2 
addError "cond3 failed" if !cond3 

checkForErrors error 

如果你應該寫的條件之前或之後addError呼叫取決於長度的檢查您的條件代碼。