Re The best code
Return to home page
Comments Loading...
2004-10-10
[Spotted in Incipient(thoughts) > http://bossavit.com/thoughts/archives/000766.html].

This is a fascinating argument stating that sometimes, code is best left duplicated.

There are very few instances like this in Smalltalk. I can only think of one case off the top of my head. That case is this:

aMethod: anArgument
self doSomethingA.
self doSomethingB.
self doSomethingC: anArgument.
self doSomethingD

And you have another method that looks like this:

secondMethod: anArgument
self doSomethingA.
self doSomethingE.
self doSomethingC: anArgument.
self doSomethingD

Now, typically, if the code has already been factored well, the methods do read like a shopping list. In the case where the two methods read like slightly varying shopping lists - I have no problem with duplication. If the methods looked like this -did- something, then I'd want to factor out the behaviour until the two methods looked like shopping lists.

The alternative is to factor out the E or B code in to something like this:

refactoredMethod: anArgument alsoDo: arbitraryYetMeaningfullyNamedBlock
self doSomethingA.
arbitraryYetMeaningfullyNamedBlock value.
self doSomethingC: anArgument.
self doSomethingD

With the other two methods becoming:

aMethod: anArgument
self refactoredMethod: anArgument alsoDo: [self doSomethingB]
secondMethod: anArgument
self refactoredMethod: anArgument alsoDo: [self doSomethingE]

I'd argue that the intent of aMethod and secondMethod have been completely lost and that it'd take some very good intention-revealing-selectors to make it "all good" for communicating the intent of this code. Perhaps trying to find the good intent names is harder than leaving it unfactored? - especially in an environment where I can easily find senders of doSomethingC: or rename it - or add an argument to it, etc.