private field v.s. parameter

  • Thread starter Thread starter JSheble
  • Start date Start date
J

JSheble

I have a class I'm writing that has aprox 20 methods, a mixture of both
public and private. Of the private methods, 3 use a database command object
(OleDbCommand) for either inserting data or selecting data. AM I better off
making the OleDbCommand object a private field to the class, or passing the
actual object to the three methods that'll be using it? Advantages?
Disadvantages?
 
I guess the question that needs to be asked is .. what functionality are you
trying to achieve by passing as a parameter? If the same command object is
passed every time then I really don't see the benefit of doing this.

Br,

Mark.
 
JSheble said:
I have a class I'm writing that has aprox 20 methods, a mixture of both
public and private. Of the private methods, 3 use a database command object
(OleDbCommand) for either inserting data or selecting data. AM I better off
making the OleDbCommand object a private field to the class, or passing the
actual object to the three methods that'll be using it? Advantages?
Disadvantages?

The fewer classes you can have which have member variables which
implement IDisposable, the better. If you have them, you really ought
to implement IDisposable yourself. If you use a parameter, you can just
do (from the calling code):

using (OleDbCommand foo = ...)
{
CallMethod (foo, ...);
}

and everything will be taken care of without you having to write your
own IDisposable implementation.
 
Hi,

Why don;t you create the object in each method ?

Or if more than one class interact with the DB you could create an object
that encapsulate the DB operations. then you export methods like this:

public static void ExecuteNonScalar( OleDbCommand)

The good thing about such a design is that in one class you concentrate all
related to connections and the others DB access related issues, the classes
only need to build a Command that they pass as a parameter.

MS also has a similar architecture, take a look at it too.

cheers,
 
Hi,

I'm of the opinion its better to pass the object through method
parameters. Most of the other methods don't care about it at all,
and you'll run less chance of 'accidently' using it when you shouldn't
if you keep things as local as possible.

I tend to keep fields only to hold the values of the classes
properties, since they represent that state of your object. The
command object doesn't represent any kind of state, you're just using
it to get work done.

I'm sure there are many other opinions, but I don't think you'll go
wrong keeping variables scoped as locally as possible.

HTH
Andy
 
I would destroy the OleDbCommand as soon as possible. The fact that you are
considering assigning it to a field suggests you are holding onto it too
long.
 
Back
Top