I often have if/else if where the blocks partially contain the same code. I would like to only have to write this code once, something like a "not else" (the else block is executed if no prior condition is met, the not else block would be executed if any prior condition is met). I know you could set a flag in each block and test if the flag is set afterwards, or create a function which is called in each block (if you dont need to edit local variables). Do you have an idea for a more clever/elegant solution? While proofreading the question I came up with the idea to return in the else block and put your common code after it - only works if you dont have to return before though.
if (condition1) {
/* unique code1 */
/* common code */
} else if (condition2) {
/* unique code2 */
/* common code */
} else if (condition3) {
/* unique code3 */
/* common code */
} else if (condition4) {
/* unique code4 */
/* common code */
}
Aucun commentaire:
Enregistrer un commentaire