Yet another error pattern  
Author Message
Filip Larsen





PostPosted: 2003-9-21 23:27:00 Top

java-programmer, Yet another error pattern Roedy Green wrote

> The problem turned out is that there is a lot of repetitive
> gobblegegook you need to make Java GUIs work. The easiest way to
> generate it is to copy paste from where you did it before, and then
> change the variable name in half a dozen places.
>
> The catch is, if you forget one of the half-dozen places the code will
> compile, but do something strange.
>
> [...]
>
> How to avoid being bitten?

I have been bitten by this copy-paste error a few times too. I find that two
things work really well for me to avoid it:

- Define variables in as narrow scope as possible. For instance, I have
often found that most of my GUI elements only need to be referenced during
construction, not during normal operation when all the listeners are set up,
so most of my buttons, menus, lists, tables, etc, are defined as final
method variables, where different parts of the GUI is constructed in
different methods. In extreme cases (like in test code) I have even break
long methods into a list of scopes to ensure that variables are not "reused"
without initialization by accident.

- If I copy more than a one or two lines, I stop and think if perhaps it
would be better to refactor the otherwise copied code into a new method.


Regards,
--
Filip Larsen