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:

Copy code// Bad:
if (player.health <= 0) {
  console.log('Game over');
} else if (player.hasCompletedLevel()) {
  console.log('Level complete');
} else {
  console.log('Keep playing');
}

// Good:
if (player.health <= 0) {
  console.log('Game over');
  return;
}

if (player.hasCompletedLevel()) {
  console.log('Level complete');
  return;
}

console.log('Keep playing');

4. Use ternary operator:

Copy code// Bad:
let message;
if (player.hasCompletedLevel()) {
  message = 'Level complete';
} else {
  message = 'Keep playing';
}

// Good:
const message = player.hasCompletedLevel() ? 'Level complete' : 'Keep playing';

5. Use object destructuring:

Copy code// Bad:
if (player.health <= 0 && player.lives === 0) {
  console.log('Game over');
// Good:
const { health, lives } = player;
if (health <= 0 && lives === 0) {
console.log('Game over');
}

Last updated