Arcade Game Example

Here is an example of how each of the refactoring techniques for if conditions could be applied in the context of an arcade game:

  1. Use descriptive variable names:

Copy code// Bad:
if (p === 'A' && q === 2) {
  // Do something
}

// Good:
if (playerMove === 'A' && enemyHealth === 2) {
  // Do something
}

2. Extract complex conditions into separate functions:

Copy code// Bad:
if (player.hasPowerUp('shield') && enemy.isWeakTo('fire') && player.fireballs > 0) {
  // Do something
}

// Good:
function canUseFireAttack(player, enemy) {
  return player.hasPowerUp('shield') && enemy.isWeakTo('fire') && player.fireballs > 0;
}

if (canUseFireAttack(player, enemy)) {
  // Do something
}

3. Use early return statements:

4. Use ternary operator:

5. Use object destructuring:

Last updated