Luhn Module: Refactoring: Extract DigitDoubler class Part 2

To follow along, you can check out the luhn-extract-digit-doubler-class-2 branch from the git repo: https://github.com/stephenaument/tactical-refactoring

$ git clone [email protected]:stephenaument/tactical-refactoring.git # If you haven't done this already
$ git checkout luhn-extract-digit-doubler-class-2

Transcript

Now that we have a set of passing tests, let’s go ahead now and refactor our DigitDoubler class by working top down as we’ve been doing for our Luhn Validator class.

First, this is a class-level convenience method. Let’s refactor what we have to an instance method.

Well, that didn’t work. What happened?

Ah, I see. Our local variable name is overriding our attr_reader name and causing problems. Let’s rename our local variable to doubled_digit.

There we go.

Now, I think I might actually have a case for a ternary expression on this return.

What I want to say is if my doubled digit is double digits, return the doubled digit - 9, otherwise return the doubled digit, itself.

Okay, what’s the smallest change to stay green?

Let’s see…doubled_digit > 9 ? doubled_digit - 9 : doubled_digit.

So let’s implement doubled_digit, taking our Integer conversion along for the ride.

Okay, that works.

Since we are already calling this method more than once, I’ll go ahead and memoize the value so we don’t have to repeat the work.

Now we can start to name some of these pieces.

We have been referring to the ternary check doubled_digt > 9 as double_digits? not to be confused with the doubled_digit. So let’s name it.

Now let’s get this magic number 9 out of our code and make it a constant. I think we should call it MAX_DIGIT.

And so the answer to the question double_digits? is that our doubled_digit is greater than the MAX_DIGIT.

And also, if it is, we want to subtract our MAX_DIGIT from the doubled_digit and return that.

We’re still green.

This looks pretty good.

I’m not going to bother with the 2 in doubled_digit because that seems like a pretty self-explanatory number. I mean, if you don’t know that doubling means multiplying by 2, you are going to have a bad time with the rest of this.

Go ahead and extract this class and its test to their own files and I’ll meet you back in our LuhnValidator to see if we have any more cleanup to do.

But we are just about done with this exercise.

Complete and Continue  
Discussion

0 comments