OOP question: Database access in class constructor

  • Thread starter Thread starter Patrick P.
  • Start date Start date
P

Patrick P.

Hello,

In an application I'm working on, I use a class in which some member
values are initialized by reading data from an SQL Server-database.

For this to achieve , I have added a procedure to the class constructor
that reads the data. As a result, the same data are read every time the
class is used. The class is used very frequently in the application, so
this leads to an unnecessary amount of database query's.
My question is how I can solve this in a way that the data are read
only one time and that the next times the data are accessed from
memory.

Any ideas?

Thanks a lot.

Patrick Pasteels
 
have a static member in your class. which will hold the copy of the data.
Read the data from the database only if your copy is null. This will enable
you to read the data first time. and subsequent calls will extract the data
from your local copy (a dataset possibly?)

Be sure to refresh the dataset whenever you want to repopulate it from the
database

HTH,

--Saurabh
 
One thing you should keep in mind, if you are writing ASP.NET code. Static
variables are shared with all users so if you need to store user specific
data then you cannot use static variable for this.

JMu
 
You create three classes: a class which reads data from the database and
makes it available to other classes, a class that forms a business
interface, and a controller class. The business object will need the
underlying data. Therefore, your business object, in its constructor, calls
the controller. The controller maintains a list of singleton objects for
reading data. It only creates an object if it doesn't already exist. It
returns an object that reads data. The business class asks the data reading
class for some data, which it returns.

The data reading class only goes to the database if it isn't already full of
data. Therefore, you essentially cache the call. Your business object is
NOT AWARE of whether the data is coming from a cache or coming from the db
directly. The controller class isn't either. I handles the creational
aspects of the object without handing the use aspects. The data reading
object is very simple: if we query the db, keep the results and the query.
If you get another request with the same query, return the existing results.

That's an OO answer.

For more ideas, see:
http://blogs.msdn.com/nickmalik/archive/2004/12/21/328727.aspx

--
--- Nick Malik [Microsoft]
MCSD, CFPS, Certified Scrummaster
http://blogs.msdn.com/nickmalik

Disclaimer: Opinions expressed in this forum are my own, and not
representative of my employer.
I do not answer questions on behalf of my employer. I'm just a
programmer helping programmers.
 
Back
Top