DRY Number Word Phrases

I recently ran into a piece of code that contained repetitive sections and I thought it could use refactoring to DRY it.

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:

  1. determine the first digit of the number by dividing by the number order,
  2. get the remainder after taking away the first digit by calculating the modulo,
  3. adding the appropriate words to the word phrase, and
  4. 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.

Advertisements

2 thoughts on “DRY Number Word Phrases

  1. Max

    I really like the first version better in my opinion. I think that, although it is more repetitive, it is easier to understand and follow. This was a really nice read and I feel like I understand DRY code better now. Thanks for sharing!

    Like

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s