Coffeescript 开关';非其他';案例
是否可以删除此代码中无用的Coffeescript 开关';非其他';案例,coffeescript,Coffeescript,是否可以删除此代码中无用的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)
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"
您可以将代码更改为
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"
缺点是重复条件检查
我猜您希望显示所有未满足的条件(因为您将process.exit调用放在switch语句之后)。如果是这样,您的代码就有一个问题,即它只显示第一个未满足的条件。所以我只使用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调用之前或之后编写条件检查取决于条件代码的长度