Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is the "with" statement dangerous?

Status
Not open for further replies.

FrankThynne

Technical User
May 29, 2001
36
0
0
GB
A colleague has heard from various Delphi developers that the Object Pascal with statement should be avoided. Why might that be? It seems to me to be an important structured statement.
 
The "with statement" is not dangerous on its own, but it does redefine the scope for the block of code.

For code that is easier to read, I tend to avoid "with statements", and explicit prefix method and property calls with the name of the object I'm using.
 
I cant think of any reason it should be avoided or dangerous. I use it from time to time when using one component for a number of operations all at the same time, most notably when using a component called VCLZip.

with VCLZip1 do begin
{Operations}
end;

Its never done anything any harm yet makes my code a darn sight easier to read when coming back to it at a later date.

Arte Et Labore
 
There are a couple of points to watch when using 'with'

You can nest and stack with's but
If you are accessing 2 components that share the same properties the the results can be unpredictable.

eg with editbox, combobox do
text := 'smeg';

The compiler wont know which components 'text' property you mean, it will apply the correct rule in this circumstance but wont let you know what it has done!.

The code insight dosent always work correctly inside a 'with' statement, so you might see a misleading pop up.

Generaly debugging is slightly harder.

With does lead to neater looking code however, so I tend to convert statements to withs
1. After I know it works OK.
2. If it is a simple piece of code anyway.

Steve



 
Every code can be dangerous, unless you know what you are doing.
With makes the code more readable and reduces repeating characters

example

for i:=1 downto 10 do Steven van Els
SAvanEls@cq-link.sr
 
...just a small thing, but it's good at shortening lines too, especially using references like (eg) with (Owner as TMainDataModule) etc.

When using more than one 'thing' in a WITH, I always thought it starts with the rightmost 'thing' and works left, as if the right most was actually nested inside another WITH, is that right?

eg

with MyLabel, MyEdit do

is equivalent to

with MyLabel do
:
with MyEdit do


lou
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top