Mega Code Archive

 
Categories / Delphi / OOP
 

Be careful when you use with statement

Title: Be careful when you use with statement Question: My code seemed right. Why a runtime error occurs? Answer: My code seemed right. Why a runtime error always occurs? I cannot debug it. This scene always is seen when you use with statement in Delphi program. See this code (copied from "Delphi 4 Developer's Guide", Ch 8, Pens.dpr) procedure TMainForm.ClearCanvas; var R: TRect; begin // Clear the contents of the canvas with Canvas do begin Brush.Style := bsSolid; Brush.Color := clWhite; GetWindowRect(Handle, R); // Error code // Right: GetWindowRect(Self.Handle, R) R.TopLeft := ScreenToClient(R.TopLeft); R.BottomRight := ScreenToClient(R.BottomRight); FillRect(R); end; end; This code seemed right, but when you try to run the program, strange thing you will look. It's very hard to find it, because use the "with" statement, the compiler takes Handle as Canvas.Handle, but you take it for granted that Handle is MainForm.Handle. This is the difference. The tooltip expression evaluation also give you wrong answer when you use "with" statement, and you move mouse on the "Handle", what you get is MainForm.Handle, not the Canvas.Handle. From the example, you can know the "with" statement can produce a very simple bug but it is very hard to find it. Although "with" statement will reduce much more typing when you program, it's side-effect is also strong. Now Delphi IDE support code-complete (just press Ctrl+Space), it's also reduce more typing. Summary: When you use the "with" statement, be sure that you code is very very right, otherwise don't use "with" at all, writes it directly.