Have an amazing solution built in RAD Studio? Let us know. Looking for discounts? Visit our Special Offers page!
News

Delphi With Statements and Local Variables

I was recently discussing against the use of the with statement in Delphi with a customer and I realized that local variables offer a very good way to get rid of with statements


As any Delphi developer knows, the with statements have been long in the Object Pascal language since the early Pascal days, but they have also been considered harmful by many, myself included. To explain once more why, I’ll use a classic piece of code highlighting the issues with scope:

withlvar_01-6597961

What does this code? It creates a button at the position of the mouse click (or mouse down, to be more precise) on a form, setting the form at parent, using the button’s class name as caption and turning its color to red. Well, this is what one might assume the last line of code to do, but it is in fact badly incorrect, producing this output:

withlvar_02-8803930

Given the TButton class has no Color property, the compiler assumes Color refers to the current object of the method, that is the form. With statements add an object in the direct scope, but offer no way to differentiate between an operation on the object part of the with or the self object of the current method. This is fairly dangerous in a complex application.

The “modern” alternative to do repeated operations on a temporary variable is to use an inline variable. The code is very similar, but by prefixing each operation on TButton with the variable itself, the developer makes it clear to the compiler what she or he wants to achieve:

withlvar_03-4869947

In case one attempts to assign the Color to the button, the compiler catches it and shows an error, which is a significant advantage compared to changing the Color of some other object.

Now to the original request: Are you going to remove the with statement from the Object Pascal language in Delphi? This is most likely not going to happen any time soon, but there have been requests to introduce an optional warning, so that the compiler can indicate whether you are using with in your code.

See What's New in 12.2 Athens See What's New in 12.2 Athens Dev Days of Summer 2-24

Reduce development time and get to market faster with RAD Studio, Delphi, or C++Builder.
Design. Code. Compile. Deploy.
Start Free Trial   Upgrade Today

   Free Delphi Community Edition   Free C++Builder Community Edition

About author

Marco is one of the RAD Studio Product Managers, focused on Delphi. He's the best selling author of over 20 books on Delphi.

18 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

IN THE ARTICLES