Wiki Home

With Endwith


Namespace: WIN_COM_API
WITH ... ENDWITH provides a convenient way to specify a number of properties/methods for a single object. (vfp help)
Here's a tidbit overlooked in my "WITH Aplomb" article many years ago: Do you ever write code like this:
LOCAL loObj
loObj = CREATEOBJECT("SomeClass")
WITH loObj
  .PropertyX = "some val"
  .MethodY()  && more lines like this...
ENDWITH  && done with object here

Turns out you don't need the LOCAL variable at all. Simply replace the first 3 lines with:
WITH CREATEOBJECT("SomeClass")

Randy Pearson
Interesting things:
With This
	.Test()
Endwith
Function Test
	? .Name
Endfunc

I'm not so sure how "Interesting" that is. IMO WITH as used in the above example is very dangerous. Here's all it would take for a potentially difficult debugging session: Forget to preface some property with a specific object reference and have the same property in both objects.

Function Test
  LOCAL loOtherObject
  loOtherObject = CreateObject("SomeOtherObject")

  ?.Name && refers to the THIS (whatever that was)
  ?.OtherProperty && forgot to include loOtherObject, now accesses THIS.OtherProperty by accident!
Endfunc


If
.OtherProperty
existed in the THIS from the calling code, assigns and accesses could be firing and who knows how far removed the called code could be from the calling code.

It seems it would be much better to pass THIS to the Test function like ... uh ... THIS ;)

Function Test
  LPARAMETERS m.toThatObject
  LOCAL loOtherObject
  loOtherObject = CreateObject("SomeOtherObject")

  ?m.toThatObject.Name
  ?.OtherProperty && now crashes because there is no dangling THIS
  ?m.loOtherObject.OtherProperty && ensures I'm talking to the correct object.
Endfunc


See: Manual Garbage Collection

-- Mike Yearwood
Anyone see anything wrong with the nested with this?
ox = CreateObject("foo", "? .ClassLibrary" )

Define Class foo as Custom
Procedure init
	Lparameters tcCmd, tox
	tox = this
	With this
		? .name
		With tox
			ExecScript( tcCmd )			
		EndWith
	EndWith
EndProc
EndDefine

The problem is that tcCmd may not reference any .Parms and so no object gets passed to toX, so I need to have some toX to make the WITH tox happy. See Spt Parameters for examples. - ?cfk
Why not use a "guaranteed existing" object instead of an instance of "Custom":
DO Foo with "? .ClassLibrary"

PROCEDURE Foo
LPARAMETERS tcCmd, toX
  LOCAL loX
  loX = iif( vartype(toX)='O', toX, _SCREEN )
  WITH loX
    ExecScript( tcCmd )
  ENDWITH
ENDPROC
-- wgcs
See Also: With Leaks Locals
Contributors Carl Karsten Mike Yearwood
Category VFP Commands
( Topic last updated: 2005.12.30 10:29:52 AM )