In the last lesson we started with this:
soldier_one_dps = soldier_one["damage"] * soldier_one["attacks_per_second"]
soldier_two_dps = soldier_two["damage"] * soldier_two["attacks_per_second"]
And refactored (fancy programmer word for "re-wrote") the code to look like this:
def get_soldier_dps(soldier):
return soldier["damage"] * soldier["attacks_per_second"]
soldier_one_dps = get_soldier_dps(soldier_one)
soldier_two_dps = get_soldier_dps(soldier_two)
When code is duplicated, it can lead to problems. In our example, let's pretend our coworker (probably Allan) changed the structure of the soldier dictionary, and now the key that stores the "damage" value is called dmg.
In the first example, we would need to update two lines of code. The second example only needs to make the change in one place - we centralized the logic within the get_soldier_dps function.
Now, to be fair, it's not a big deal when two lines are the same and exist right next to each other. But imagine if we had done this several hundred times in ten or twenty different code files! All of a sudden, it makes a lot of sense to stop repeating yourself and write more reusable functions.