Which objects to make global, which to make local?

℡╲_俬逩灬. 提交于 2019-12-13 04:26:03

问题


To avoid the moderators who don't like general questions, this is a Visio VBA one but I didn't want to include that in the title as it's a bit niche, and I guess the answer might be generic :-)

My code has the following variables:

Public gappVisio As Visio.Application
Public gdocFile As Visio.Document
Public gpagDiagram As Visio.Page

For those unfamilar with Visio, you create an application object, open the document, then set a reference to a page in the document where you can actually do some drawing.

All vars are global, but actually gdocFile is only used in my initialisation routine. So my question is, do I need gdocFile as global, or can I just make it local? I suppose I was worried that if it was local when it went out of scope it might tidy up the Document object, but I still need the page of the document?

Does that make sense?


回答1:


Don't make a variable or object global unless you absolutely have to, which is almost never. Pass object references as parameters to those procedures that need them -- and only to those. Anything you need from the object before it "runs out of scope", as you say, should be passed to the calling procedure as Function return value (or, more obscurely hence less preferably, Sub ByRef parameter value).

When you say an object is out of scope, it's actually the reference to that object that is out of scope. The object still exists unaltered in memory.

Generally, global is bad and leads to difficult-to-maintain code, but exceptions could be things like universal constants, e.g.

Public Const PI As Double = 3.14159265358979

It's fine to have that as global.




回答2:


In your case, the document lifetime is controlled by Visio application, the doc will not get cleaned up, no matter how many variables which refer to it you create, or in which scopes they are (global or local). Means, all reference counting (scoping) rules are simply ignored by Visio for documents in fact - the doc is not destroyed, even if there are no more references to it from your code.

You can tell Visio to close the document using document.close. After that call, any attempt to use document's (or page's) methods or properties using any of doc/page variables referring this document/page in this document will result in exception.

A doc may be closed by user. In this case all variables referring to it (or objects inside of it, such as pages or shapes) will become invalid.



来源:https://stackoverflow.com/questions/20023693/which-objects-to-make-global-which-to-make-local

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!