When, What, Why!

A common pattern seen in Delphi code is the “code inside an event handler” syndrome. Lines and lines of code are placed inside an event handler. Not enough, these event handlers are often called directly from other places in the code – just because the code inside it needs to be executed. Take that as a big sign of code smell!

You know what? The event handler is not the right place for that code.

Extract it into a separate method – or probably more of them. Name those methods so that the name describes what the code executed is supposed to do. (It is probably not doing that, but that is a case for debugging.)

You can give some extended description in a comment to the method. If you have Document Insight (you should have the Express version with any recent Delphi), use it to display this comment wherever you hover the mouse over that method name.

Place the method calls into the event handlers. May be, you can write a little comment that explains why you are calling these methods. Don’t reword the method names here.

Remember: The event handler names tell you when that code is executed, the method names tell you what is executed and the comments tell you why it is executed.

BTW: Don’t try to be clever and rename the event handler so that its name resembles the what. You will have a hard time to find out the when! It would only be stored in the event wiring of the DFM and needs the Object Inspector to see it. It only makes the code harder to read. Keep the event handler names as given when possible. In case it is wired to multiple events, name it according to its usage (like DataSetsAfterPost), not its purpose.

Author: Uwe Raabe

Addicted to Pascal/Delphi since the late 70's

3 thoughts on “When, What, Why!”

  1. A little to hard and fast for me. There is perfectly fine actual “event code” that can be included. In fact extracting some “event related code” is improper development.

  2. I agree that code which can also be useful outside the event handler should be refactored to separate methods. However, when the code is valid only for use in the event handler, I consider that extracting it is a risk, and arbitrary.

    If I extract such code, then at the very least, I would need to use naming conventions which make plain that it is really only for use inside that event handler.

    By the way, this editor behaves very oddly in Chrome. Long lines cause the editor to scroll left, but the editor does not seem properly contained. That is, what looks like a border on the right is routinely exceeded.

Comments are closed.