October 3, 2017
Manual Refactoring : Introduce FieldNext in my series on manual refactoring is a variation on Introduce Local Variable, where we want the result of an expression to be shared among methods: Introduce Field.
Consider an example where we have an object creation expression repeated in 3 unit tests.
I want to refactor this code so that the knowledge of object creation is in just one place, and because all 3 tests need to access the result, it'll need to be a field.
Like when I introduced a local variable, I'll start by cutting the whole expression and replacing it with a reference to the field-to-be.
Then I can declare the field and paste the creation expression as its initial value.
NOW RUN THE TESTS!
Next, I replace the other 2 duplicated expressions with a reference to the new field.
AND RUN THE TESTS AGAIN!
Of course, there's some wiggle room here. I could also have initialised the field in a constructor.
Or I could have initialised it using a set-up method.
But I went for the simplest solution, which works fine in this situation because:
a. Fibonacci is stateless, and its set-up is simple, and...
b. JUnit instantiates the fixture for every test anyway
Posted 1 year, 7 months ago on October 3, 2017