## Re: Duplication vs Intention Revealing code (was: Zen Refactoring)

Expand Messages
• ... My *EVIL Twin* did it. ;- ... Actually, I just realized this morning that fourty is wrong; I need to learn to spell. :-O But it handles fifty and all
Message 1 of 42 , Jun 1, 2005
--- Tony Byrne <yahoogroups@b...> wrote:
> Oh my deity, what have I started? :-)

My *EVIL Twin* did it. ;->

> JG> I can go on to bigger numbers, but I see duplication here:
> JG> - The two "base 10" numbers, used to separate "tens"
> from "ones".
> JG> - That "four" and "four-teen" and "four-ty" is duplication.
>
> Now that's a new insight for me! It never occurred to me to
> programmatically handle the appending of 'teen' or 'ty'. Mind you
> won't 'Fivety' be wrong?

Actually, I just realized this morning that "fourty" is wrong; I
need to learn to spell. :-O But it handles fifty and all the
others correctly.

The pattern is pretty strong for 6 through 9: six, six-teen, six-
ty, ... But there are plenty of exceptions, which is why I end up
with this code, to deal with the exceptions (after my spelling
correction, this morning ;-)

final String[] digitPrefixes = new String[]
{"twen~", "thir~", "for~", "fif~"};
if (digit == 4 && teens || digit > 5) {
return asWords(digit);
} else {
final String prefix = digitPrefixes[digit - 2];
final String prefixSansTilde = prefix.substring(0, prefix.length
() - 1);
return prefixSansTilde;
}

...meaning that it's "three", "thir-teen", "thir-ty", ...

"twelve" and "forty" require special handling, as do the double 't's
in "eight-teen" and "eight-ty".

In all, it ends up being a tangled, difficult-to-maintain mess, as
shown by the flag I had to introduce this morning to correct the
spelling error of "fourty" -> "forty". This change was easiest to
make in "version 1" of the code. ;->
• ... One way I ve found to avoid this is to use IntelliJ s awkwardly named Replace Method Code Duplicates refactoring. It looks for all blocks of code that
Message 42 of 42 , Jun 4, 2005
On 6/1/05, Elizabeth Keogh <ekeogh@...> wrote:
> I've extracted a method from a test, then applied the extraction to a
> similar chunk in another test, but missed out one of the parameters which

One way I've found to avoid this is to use IntelliJ's awkwardly named
"Replace Method Code Duplicates" refactoring. It looks for all blocks
of code that have the same structure as the contents of the method,
and replaces them with a call to that method. It's the natural
successor to Extract Method -- perhaps a better name would be "Apply
Method". It's not perfect, but when it works it's a thing of beauty.

Yesterday it saved us from just the problem you mentioned. We tried to
apply it and it *didn't* select the code we thought it would; it
turned out we'd missed a parameter. Once we introduced that parameter
it worked. If we'd been doing this by hand we'd have made your
mistake.

- A
Your message has been successfully submitted and would be delivered to recipients shortly.