mercredi 20 mars 2019

DRY up simple conditionals with some shared action

I need to test two conditions. Either could be true (but not both). If neither are true, we do nothing. If either are true, we perform a common action. If the second condition is true, we perform an additional action. Seems simple enough, but as I try to write the code, I find myself repeating either the condition or the action, and it doesn't feel as DRY as it might be.

To illustrate with pseudocode…

We repeat one of the conditions:

if a | b {
    do  x
    if b {
        do y
    }
}

Or, we repeat one of the actions:

if a {
    do x
} else if b {
    do x
    do y
}

I might not stop to worry about this normally, except that both conditionals and actions are one-liners that process regular expressions—complex enough to not want to repeat them, but too short to warrant their own functions.

I could throw a boolean variable into the mix …

var doX = false
if a {
    doX = true
} else if b {
    doX = true
    do y
}
if doX {
    do x
}

… but that feels a bit kludgy.

Is there a DRYer way of doing this—some beautiful, concise conditional logic that I haven't thought of? (I'm working in JavaScript at the moment, but I'm happy for a better example in any language.)

PS. I feel a bit foolish asking such a basic question—as if the answer (whatever it is) should be obvious—and I'm very happy to delete it, should that be the community consensus. But I recall that someone once said, 'He who asks a question is a fool for a minute, he who does not ask is a fool for life.'

Aucun commentaire:

Enregistrer un commentaire