This Python code passage converts an integer expressed in digits into the the same integer expressed as words. The method “in_words” uses two dictionaries:
The repetition occurs when we apply a similar sequence of steps for the number orders 1000, 100, 20, and 1:
The repeated steps serve to:
- determine the first digit of the number by dividing by the number order,
- get the remainder after taking away the first digit by calculating the modulo,
- adding the appropriate words to the word phrase, and
- adding a separator if there are more words to be added to the word phrase.
The DRY, refactored code is as follows:
In this passage, we have extracted the above steps into a method “process_digit”, and we call this method for each number order: 1000, 100, 10, and 1.
The problem is, because there are special cases to be handled, when the number is greater than 100 or when the number is greater than 20, the resulting code is a little harder to understand. The added complexity of nesting two methods instead of one linear method adds to the perceived difficulty of the new code passage.
Which version of the code is better? Leave your comment by hitting the link below the title.