473,718 Members | 2,087 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

do i need to set objects to nothing

Hi Folk

I have about 1000 procedures in my project. Many, many of them are along
the lines of

function myfuntion () as boolean
on error goto er
'-
Dim Dbs as dao.database
Dim Rst as dao.recordset
Dim SqlS as string
'-
sqls = "..."
set dbs = currentdb
set rst = dbs.openrecords et(sqls)
do while not rst.eof
.....
rst.movenext
loop
'-
xt:
exit function
er:
msgbox error$
resume xt
end function
Should set dbs and rst to nothing or is that not necessary. If so, does
anyone know of an easy way to update all my procedures at once?

TIA

- Nicolaas
Nov 13 '05
106 6450
On Sat, 14 May 2005 12:45:23 +1200, "xtra" <wi**********@h ottermail.com>
wrote:
Hi Folk

I have about 1000 procedures in my project. Many, many of them are along
the lines of

function myfuntion () as boolean
on error goto er
'-
Dim Dbs as dao.database
Dim Rst as dao.recordset
Dim SqlS as string
'-
sqls = "..."
set dbs = currentdb
set rst = dbs.openrecords et(sqls)
do while not rst.eof
.....
rst.movenext
loop
'-
xt:
exit function
er:
msgbox error$
resume xt
end function
Should set dbs and rst to nothing or is that not necessary. If so, does
anyone know of an easy way to update all my procedures at once?

TIA

- Nicolaas


OK, you've read all the posts saying that you do have to close and release
your DAO objects at a minimum, and perhaps other COM objects as well, but
reference counting does work correctly for internally defined objects.

There's a technique I've finally arrived at that uses the 2 pieces of
information above to create a simple, bullet proof way to make sure everything
gets cleaned up.

1. Make sure every procedure is covered by error handling. It can have its
own error handler or it can be called by something else that has an error
handler. That's because, if the code is ever reset, nothing your code does
can force proper clean-up, and having error handlers mostly prevents that. A
good rule of thumb is, put error handlers in your application start-up routine
and in every event handler. All other error handling is optional (and to be
avoided when as possible to keep code simpler).

2. Encapsulate every COM object within an instance of an internally defined
wrapper class, and have the terminate handler of the class explicitly close
and release the encapsulated object. Note that this termination handler will
fire whenever the object goes out of scope, even if that happens because a
procedure errored out, and the error was captured farther up the call stack.

3. Make sure every wrapper class also holds a reference to the wrapper class
of any object the thing it wraps depends on. That means the "parent" wrapper
can't go out of scope before the child. For instance, the DAO.Database
wrapper can't go out of scope before the DAO.Recordset wrapper that depends on
it.

It takes a bit of work to set this up initially, but then all the rest of your
code becomes much simpler. You no longer have to analyze each procedure to
make sure it will do its clean-up properly, and you don't have to write
additional error handlers just to force that to happen.

More specifics on wrappers...

First, once you have wrappers working, don't store references to the unwrapped
objects. That leads right back to the kinds of problems we wrote the wrappers
to avoid in the first place.

You don't need to make the wrappers wrap every method of the wrapped object
(that's excessive duplication), just provide an accessor to the wrapped
object. The wrappers do make great places to add helper functions though,
such as a way to get the names of missing query parameters to report a
meaningful error instead of ("2 parameters expected ...").

Since you'll be using the wrapper and the accessor a lot, use a short naming
convention for each.

When objects go out of scope, having dependent objects hold reference to their
dependencies forces the correct clean-up order, but if we allow actions that
can reset an object's state we need a way to force the dependent objects to
reset first. To do that, we use the VB/VBA Event mechanism. This doesn't
work in Access 97. You can make this safe in Access 97 by disabling actions
that can cause reset. Just check to see if the object is already set up, and
raise an error on any attempt to do anything that would reset the wrapped
object.

Here's a simplified, example (code is not tested, but does compile
successfully):

== clsDbsWrapper ==

Option Compare Database
Option Explicit

Private mdbs As DAO.Database
Private mblnCloseOnTerm inate As Boolean

Public Event RequestReset()

Public Sub UseCurrentDb()
Reset
Set mdbs = CurrentDb
mblnCloseOnTerm inate = False
End Sub

Public Sub OpenDb( _
Name As String, _
Optional Options As Variant, _
Optional ReadOnly As Variant, _
Optional Connect As Variant _
)
Reset
Set mdbs = DBEngine.OpenDa tabase(Name, Options, ReadOnly, Connect)
mblnCloseOnTerm inate = True
End Sub

Public Property Get dbs() As DAO.Database
Set dbs = mdbs
End Property

Public Function NewRstWrapper() As clsRstWrapper
Dim objRstWrapper As New clsRstWrapper
objRstWrapper.S etup Me
Set NewRstWrapper = objRstWrapper
End Function

Public Sub Reset()
' Tell dependent objects to reset first
RaiseEvent RequestReset

If mdbs Is Nothing Then Exit Sub

If mblnCloseOnTerm inate Then
mdbs.Close
End If

Set mdbs = Nothing
End Sub

Private Sub Class_Terminate ()
Reset
End Sub
== clsRstWrapper ==

Option Compare Database
Option Explicit

Private WithEvents mobjDbsWrapper As clsDbsWrapper
Private mrst As DAO.Recordset

Public Event RequestReset()

Public Sub Setup(objDbsWra pper As clsDbsWrapper)
Reset
Set mobjDbsWrapper = objDbsWrapper
End Sub

Public Sub OpenRst( _
Name As String, _
Optional RstType As Variant, _
Optional Options As Variant, _
Optional LockEdit As Variant _
)
Reset
Set mrst = mobjDbsWrapper. dbs.OpenRecords et( _
Name, RstType, Options, LockEdit)
End Sub

Public Property Get rst() As DAO.Recordset
Set rst = mrst
End Property

Public Sub Reset()
' Tell dependent objects to reset first
RaiseEvent RequestReset

If mrst Is Nothing Then Exit Sub

mrst.Close
Set mrst = Nothing

End Sub

Private Sub mobjDbsWrapper_ RequestReset()
Reset
End Sub

Private Sub Class_Terminate ()
Reset
End Sub

Nov 13 '05 #11
"Lyle Fairfield" <ly******@yahoo .ca> wrote in message
news:q0******** *********@read1 .cgocable.net.. .
If I were doing the code writing I would examine my code carefully and
write code to change it by

1. removing redundant DAO references eg. SET db=CurrentDB


What's the problem with that?

Is it meant to be something like:

rst = CurrentDB.openr ecordset

?
Nov 13 '05 #12
Mike MacSween wrote:
"Lyle Fairfield" <ly******@yahoo .ca> wrote in message
news:q0******** *********@read1 .cgocable.net.. .

If I were doing the code writing I would examine my code carefully and
write code to change it by

1. removing redundant DAO references eg. SET db=CurrentDB

What's the problem with that?

Is it meant to be something like:

rst = CurrentDB.openr ecordset


That very quickly goes out of scope, the next line using rst will fail.

--
[Oo=w=oO]

Nov 13 '05 #13
Tom van Stiphout wrote:
BTW, this is one of the main reasons .NET does NOT use reference
counting. Everyone (including MSFT) now agrees that it was a bad idea,
requiring too much dilligence on the part of the developer. The smart
marketeers now sell the garbage collector in .NET as the best thing
since sliced bread. It performs the same function as
rst.Close
set rst = Nothing
without you ever having to worry about it.


Ah great, another language platform to encourage sloppy coding.

Whilst it's nice to not have to set a variable to nothing (we don't set
our ints to 0 and strings to "" at the end) I think a programmer should
at least close a recordset he has opened.

Sooner or later, a programmer may get another job and have to write a
program in another language that may be a lot stricter, they will then
fall foul of it.

--
[Oo=w=oO]

Nov 13 '05 #14
xtra wrote:
Function GC ()
for each object
if object.name = rst
rst.close
set rst = nothing
end if
next object
end function
????

That would solve my problem as all my functions end in


It may close the recordsets (not tested) but will definately not release
the object variables as all you're doing there is creating new ones to
point at the ones that weren't cleaned up (assuming they were able to
point at them).

--
[Oo=w=oO]

Nov 13 '05 #15
Mike MacSween wrote:
"Lyle Fairfield" <ly******@yahoo .ca> wrote in message
news:q0******** *********@read1 .cgocable.net.. .

If I were doing the code writing I would examine my code carefully and
write code to change it by

1. removing redundant DAO references eg. SET db=CurrentDB

What's the problem with that?

Is it meant to be something like:

rst = CurrentDB.openr ecordset


hmmm ... It was late; I was recommending converting everything to ADO.
Therefore DAO references would be redundant.
--
--
Lyle

"The aim of those who try to control thought is always the same. They
find one single explanation of the world, one system of thought and
action that will (they believe) cover everything; and then they try to
impose that on all thinking people."
- Gilbert Highet
Nov 13 '05 #16
"Lyle Fairfield" <ly******@yahoo .ca> wrote in message
news:d7******** ********@read1. cgocable.net...
hmmm ... It was late; I was recommending converting everything to ADO.
Therefore DAO references would be redundant.


Got ya
Nov 13 '05 #17
On Sat, 14 May 2005 10:34:06 +0100, Trevor Best <no****@besty.o rg.uk> wrote:
Tom van Stiphout wrote:
BTW, this is one of the main reasons .NET does NOT use reference
counting. Everyone (including MSFT) now agrees that it was a bad idea,
requiring too much dilligence on the part of the developer. The smart
marketeers now sell the garbage collector in .NET as the best thing
since sliced bread. It performs the same function as
rst.Close
set rst = Nothing
without you ever having to worry about it.


Ah great, another language platform to encourage sloppy coding.

Whilst it's nice to not have to set a variable to nothing (we don't set
our ints to 0 and strings to "" at the end) I think a programmer should
at least close a recordset he has opened.

Sooner or later, a programmer may get another job and have to write a
program in another language that may be a lot stricter, they will then
fall foul of it.


To me, that's like saying we should make programmers deal with pointers
correctly because they may eventually have to code in C. To me, any way a
language can get junk out of the way, so a program has, as much as possible,
just logic about the application and not about the system, that's a good
thing.
Nov 13 '05 #18
Steve Jorgensen <no****@nospam. nospam> wrote in
news:dm******** *************** *********@4ax.c om:
A
good rule of thumb is, put error handlers in your application
start-up routine and in every event handler. All other error
handling is optional (and to be avoided when as possible to keep
code simpler).


Er, I don't think you typed what you meant to type.

--
David W. Fenton http://www.bway.net/~dfenton
dfenton at bway dot net http://www.bway.net/~dfassoc
Nov 13 '05 #19
Lyle Fairfield <ly******@yahoo .ca> wrote in
news:wt******** ********@read1. cgocable.net:
IMO, while Access is a fine GUI, DAO and VBA are archaic, clumsy
and inefficient.


Well, from where I sit, technologies like ADO are so advanced and
up-to-date and sleekly designed that they guess what I mean to do
and end up getting results that are not what I would have intended.

--
David W. Fenton http://www.bway.net/~dfenton
dfenton at bway dot net http://www.bway.net/~dfassoc
Nov 13 '05 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1931
by: Bobby | last post by:
Hello everyone I have a question. The school I am working for is in the beginning process of having a webpage that will direct students to download there homework and be able to view there info like test scores and etc(the homework and info page will reside on our webservers at the school on the local intranet network). Now what I need is a way for the students to go to a login page and when logging in will be automatically directed to...
2
1790
by: Lin Ma | last post by:
Hello, I have a general question. In my asp page, I have DB connection, Recordset, and some variables like dim name, conn, rs set conn = Server.CreateObject("ADODB.Connection") .... set rs= server.createObject("ADODB.Recordset")
16
2207
by: Joel Finkel | last post by:
Folks, I am confused as to how to implement the following solution. I have a series of processing steps, each of which contains similar features (forms, etc). Therefore, I create a base class, Step, and subclass from that for specific steps. The Step class has a method, Execute(), which can return either Success or Failure. I have a Step Driver, which instantiates the first Step, calls its Execute()
5
3788
by: Learner | last post by:
Hello, Here is the code snippet I got strucked at. I am unable to convert the below line of code to its equavalent vb.net code. could some one please help me with this? static public List<RoleData> GetRoles() { return GetRoles(null, false); }
18
2333
by: bsruth | last post by:
I tried for an hour to find some reference to concrete information on why this particular inheritance implementation is a bad idea, but couldn't. So I'm sorry if this has been answered before. Here's the scenario: We have a base class with all virtual functions. We'll call this the Animal class. We then make two classes Fish and Bird that both inherit from Animal. In the program, we have a single array of Animal pointers that will...
4
14912
by: Paul H | last post by:
A typical chunk of code...... Set db = CurrentDb Set rs = db.OpenRecordset("tblFoo") <Do some stuff here> 'How much of the stuff below do I need? 'Do I need to close the recordset? rs.Close
9
3942
by: pic078 via AccessMonster.com | last post by:
I need serious help - I have a frontend/backend Access database (2 MDE Files) that remains stuck in task manager after exiting the application - you can't reopen database after exiting as a result - I have read every post out there and spent hours trying to figure out the problem with no success whatsoever - I have constrained the problem to one form however, and I think it's hiding somewhere in my code associated with this form, which is...
1
7109
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that someone who bothers to read all of it have some pointers. Note, I have posted the stack trace and the code exhibiting the problem further down so if you want to start by reading that, search for +++ Also note that I am unable to reproduce...
167
8302
by: darren | last post by:
Hi I have to write a multi-threaded program. I decided to take an OO approach to it. I had the idea to wrap up all of the thread functions in a mix-in class called Threadable. Then when an object should run in its own thread, it should implement this mix-in class. Does this sound like plausible design decision? I'm surprised that C++ doesn't have such functionality, say in its STL. This absence of a thread/object relationship in...
0
8827
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8724
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9207
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9121
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5971
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4481
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4743
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2122
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.