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:
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:
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:
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.