More and more I realize my code is getting filled with if/else statements. Eventually, I started to write one-liners (x = 'this' if y > 0 else 'that'
) and, in some cases, if a test were often true, I assumed it was from the beginning and only changed anything if it weren't. For example:
From this
def increase_score(self, side)
if self.player.side == side:
self.enemy.score += 1
else:
self.player.score += 1
I would do this
def increase_score(self, side)
# assume player.side is side
last_enemy_score = self.enemy.score
self.enemy.score += 1
# only change if player.side isn't side
if self.player.side != side:
self.enemy.score = last_enemy_score
self.player.score += 1
Besides these two approaches, what are some interesting alternatives to line-by-line if/else statements?