My example today is Tom Oram's 2018-11-11 essay on Uncle Bob's Transformation Priority Premise. Oram uses four tests and seven distinct implementations of even?
If he were refactoring aggressively, I think we would see three implementations from two tests.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Test: expect(even?(1)).to be(false) | |
# Transformation: nil -> constant | |
# This is Oram's original implementation, unchanged | |
def even?(number) | |
false | |
end | |
# Refactor | |
# Let's be explicit about why `false` is the correct answer here | |
# WITHOUT changing the observable behavior | |
def even?(number) | |
1 % 2 == 0 | |
end | |
# Test: expect(even?(2)).to be(true) | |
# Transformation: constant -> scalar | |
# This is Oram's final implementation, unchanged | |
def even?(number) | |
number % 2 == 0 | |
end |
Kent Beck, in the face of objections to such a refactoring under the auspices of "removing duplication", wrote:
Sorry. I really really really am just locally removing duplication,At that time, Beck was a bit undisciplined with his definition of "refactoring". Faced with the same problem, my guess is that he would have performed the constant -> scalar transformation during his "refactoring" step. If there isn't a test, then it's not observable behavior?
data duplication, between the tests and the code. The nicely general formula
that results is a happy accident, and doesn't always appear. More often than
not, though, it does.
No instant mental triangulation. No looking forward to future test cases.
Simple removal of duplication. I get it now that other people don't think
this way. Believe me, I get it. Now I have to decide whether to begin
doubting myself, or just patiently wait for most of the rest of the world to
catch up. No contest--I can be patient.
Personally, I find that the disciplined approach reduces error rates.
No comments:
Post a Comment