Sie sind auf Seite 1von 1

# Avoiding Anti-Patterns

# Author: TODO: ????

# EXAMPLE: critical battery level

# Anti-pattern / Magic numbers: Including unexplained numbers in algorithms

current_battery_level = 20 # as percent, taken from a hardware


# TODO: run the program with different values

if current_battery_level < 15:


print("Charge your mobile phone!")

# Solution: Avoiding magic numbers by defining constant values

CRITICAL_BATTERY_LEVEL = 15

current_battery_level = 25
# TODO: run the program with different values

if current_battery_level < CRITICAL_BATTERY_LEVEL:


print("Charge your mobile phone!")

# TASK: Traffic lights

color = 0xFFFF00 # yellow color coded as a RGB (red green blue) in a hexadecimal
number.
# It seems to be a magic number, but you can easily reveal the meaning of it.
# However, it is better to replace it wih constant value in case you would need to
change it later.

mode = 0 # flashing mode coded as 2, other modes could be 0 for off, 1 for on

if color == 0xFFFF00 and mode == 2:


print("yellow flashing active")

# TODO: propose an improved variant of the conditional expression

Das könnte Ihnen auch gefallen