Here is an example of how each of the refactoring techniques for if conditions could be applied in the context of an arcade game:
Copy code// Bad:
if (p === 'A' && q === 2) {
// Do something
}
// Good:
if (playerMove === 'A' && enemyHealth === 2) {
// Do something
}
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
}
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');
Copy code// Bad:
let message;
if (player.hasCompletedLevel()) {
message = 'Level complete';
} else {
message = 'Keep playing';
}
// Good:
const message = player.hasCompletedLevel() ? 'Level complete' : 'Keep playing';
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');
}