Friday, March 24, 2006

Does Code Duplication Have To Be A Bad Thing?

This is a bit of a crazy idea. I'm curious what anyone reading this blog might think about it...

The project I am currently working on validates the data coming from forms and imports in the domain. If you try to save a record with bad data in it, the domain will catch the error. The users also want irrelevant fields not to appear on the screen. A generic example would go something like this: Let's say you have a form which lets you enter a sales person's total sales for the month. If the sales exceed a certain threshold, then you can enter in a bonus. The back end of the system validates the bonus. It makes sure that you are not allowed to enter a bonus if the total sales are too low. The customer also requests that the screen not show the entry field for the bonus if the sales entered are too low. There are a couple of options I can think of: In one case, you drive the screen code from the domain validation logic. Otherwise you can duplicate the logic, e.g.

In the form code:

if (totalSales > MIN_BONUS_SALES) {
displayBonusField();

}

In the back-end domain code:

if (totalSales < MIN_BONUS_SALES) {
createNotEnoughSalesError();
}

This is bad because it means you have to maintain this logic in two places. What if the development environment allowed you to set up dependencies so you could still maintain the duplicate code, but the compiler would warn you if you changed code in one function and not the other? e.g.

In the form code:

@depends_on SalesPerson.validateBonus
if (totalSales > MIN_BONUS_SALES) {
displayBonusField();

}

In the back-end domain code:

validateBonus() {

if (totalSales < MIN_BONUS_SALES) {
createNotEnoughSalesError();
}
}


The point I'm making is that just updating both pieces of code isn't really a big problem, but knowing about all of the dependencies is. The normal way of dealing with it is to remove the dependencies and to develop a code framework that allows these ideas to be maintained in one place, but that can mean more work than one might want to do. I wonder if enabling tools to help manage code dependencies like this would be a viable option.

1 comment:

Daniel S. said...

Annotations to help with code duplication sounds a bit dangerous to me. But that probably depends on the programmers self-discipline. Your example doesn't involve too much code and is not the standard copy/paste duplication I've seen in some projects. Maybe your idea (no pun intended) will appeal to the IntelliJ community who has been asking so much from their IDE. Nice to be able to stay in touch thru your blog.


Daniel