When you notice repeated code, an appropriate refactoring may be to inline your code. Learn how to eliminate a superfluous variable declaration by inlining it.
- [Instructor] Let's continue solving the kyote. Our next text case will be for the Roman numeral V. (typing) We'll convert V and write a test to make sure that V returns five. We'll run the tests. We have a red test result as expected. This is the red step in the red green refactor three step dance.
Now let's write the least amount of code to make it go green. Say if Roman numeral equals I, then return one, else return five.
Re-run the tests, and it's all green. Looks like there's nothing to improve here, so we'll go on to the next test case. We'll add another test that goes red. We'll say arabic equals Roman.convert on X, that's the next Roman numeral. Assert equals 10, X is supposed to get converted into 10. Run the tests.
It's red because we haven't implemented that solution code yet, so now we'll write the simplest code that will make that test go green. Else if Roman numeral equals five, equals V, return five, else return 10. Run the tests, and it's all green.
Now we're at the refactor step of the red green refactor three step dance. I'm noticing some repeated code here. This is a code smell called Don't Repeat Yourself or DRY. Repeated code is difficult to maintain, it decreases our technical agility. If we need to make a change to one of these lines of repeated code, we'll have to make that change over and over, it will slow us down. We'll do a refactoring here to inline some of this code.
Right click on arabic at line 23, refactor, and inline. This is going to replace that variable at line 23 with the value that we assigned it to at line 22 and remove line 22. Click refactor to make that happen. And then re-run the tests to make sure that we didn't change any of the external behavior. And it's all green. Repeat that step at line 20, right click, refactor inline, quick refactor again to confirm that's what we want.
It eliminated line 19, put that inline, run the tests again, make sure we're still green. And one more time at line 17. Right click arabic, refactor, inline, confirm, re-run the test to make sure we didn't change any external behavior, and we're still green. One last thing, we'll beautify this code a little bit. Delete line 17, delete line 18.
We didn't change any code, but I'm still going to re-run the tests, just in case, just to be super careful and make sure we didn't change any external behavior. Everything is still green, so we're all set.
- Defining refactoring
- Setting up a test-driven development environment
- Renaming variables
- Using the extract method
- Pinning down legacy code
- Testing code and branch coverage
- Refactoring legacy code
- Simplifying math and Booleans
- Adding new behaviors to refactored code