user619271
user619271

Reputation: 5022

Switch 'non-else' case?

Is it possible to get rid of useless ok variable in this code?

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"

Upvotes: 1

Views: 60

Answers (1)

Sascha
Sascha

Reputation: 1156

You may change your code to

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"

with the disadvantage of duplicating the condition checking.

I guess that you want to show all unmet conditions (because you put the process.exit call after the switch statement). If so, your code has the problem that it does only shows the first unfulfilled condition. So I would just use if statements

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"

All over all you'll have to decide if the double checking of your conditions or one setting and checking of a variable is more expensive in comparison with the readability of your code.

I would give readability a higher priority if not realy dealing with performance or memory problems an use something like:

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

If you should write the condition checking before or after the addError call depends of the length of your condition code.

Upvotes: 1

Related Questions