Alex Rivera | Logout

How / if to refactor a Delphi program using only forms and data modules

Asked 2009-02-14T17:04:57.827
21

After years of coding Delphi programs as untestable code in forms and datamodules, including global variables, and the only classes are the forms themselves, containing all the code I need for the form UI itself.

How would I convert the code to a set of classes that do the actual work? would I need to stop using the datasources/datasets and do everything in classes? do I need an ORM?

There's usually zero need for reuse of the code in the forms, so does it make sense to convert the logic to classes?

Edit
Report

2 Answers

28

If I encounter a form (or other class) with too much responsibility, I usualy follow the pattern below:

  1. Define a new class for the logic.
  2. Create a member variable of the new class in the form.
  3. Create the class in the onCreate and free it in the onDestroy of the form.
  4. Move a single piece of logic (for example a variable) to the new class.
  5. Move or create all methods to the new class.
  6. Compile and test.
  7. Continue until all logic is put in the new class.
  8. Try to decouple the logic class from the form class. (You can even work with interfaces if you like).

There are situations where a single class is not enough, so it is no problem to create more classes. And these classes can have other classes to.

With these steps, you can tackle most of these problems.

answered 2009-02-14T19:32:25.977
4

Importing into Modelmaker is my first action when confronted with an existing Delphi project. Modelmaker will assist you in refactoring your code because:

  • It graphically represents all the classes, methods, variables, etc.
  • It is very tightly integrated in the Delphi IDE (main menu, popup menu, separate Modelmaker explorer, toolbar, keyboard shortcuts). This integration allows you to quickly perform the necessary actions without leaving the IDE
  • It has a dedicated "refactoring" module allowing you to quickly create, move and rename classes and variables without having to worry about changing the underlying code. Modelmaker will automagically change names and references in all units.

The basic functionality of Modelmaker is easy to learn. Modelmaker is like any other good productivity tool - The more you put into it, the more you get out of it. Modelmaker is not free but easily pays for itself in increased productivity. I have not found a better tool for refactoring legacy Delphi code. They offer a free trial and some decent tutorial movies. Give Modelmaker a try and good luck...

answered 2009-02-21T03:06:34.763

Your Answer