when to use static

R

RichGK

I have an abstract class that provides the basis for SQL data access
functions, with the subclasses building on this to create access to tables
via select query strings.

I have created the subclasses as static as all they contain are (for
example) a select query string, and a method to return the results of a
SqlSelect query. (SqlSelect is my own class that simply wraps the creation
of DataSet etc).

So everything in the subclass is static.

namespace DataAccess
{
public class EmployeeTDG : DataAccess.TDG
{
private static string selectString = "SELECT [name] FROM [Employee] ORDER BY
[name] ASC";
public static SqlSelect getEmployees(SqlConnection sc)
{
return TDG.executeSelectQuery(EmployeeTDG.selectString, sc);
}
}
}

My question is, is this ok? My concerns are that maybe I've overlooked
something that might bite me in the backside later!

Cheers
Rich.
 
P

Picho

Rich,

my opinion is it's ok. but:
using a string as the command is not such a good idea at least in the
security aspect.
for my understanding you should try and use stored proceadures or parameters
in the query to avoid SQL injection attacks and so on.

im no expert at this so this is just a thought but you might want to look
into that.

Picho
 
N

Nick Malik [Microsoft]

Hi Rich,
I have an abstract class that provides the basis for SQL data access
functions, with the subclasses building on this to create access to tables
via select query strings.

I have created the subclasses as static as all they contain are (for
example) a select query string, and a method to return the results of a
SqlSelect query. (SqlSelect is my own class that simply wraps the creation
of DataSet etc).

seems pretty pointless to have an abstract class and then create descendents
that are composed of static items. You don't get much from the interface
inheritance abilities of the abstract class.

You didn't say _why_ you cannot stand to use actual objects, instead of
static classes. The advantage of objects is that you are much better able
to control the coupling between classes, since the objects have to be
created in the context of the class that uses it, or passed in, which
provides you with both clues to the dependencies in the code, and
opportunities to generalize through the use of common ancestor types and
factory methods.

In other words, your message, and what small glimpse of your design that I
can glean from it, indicates that you may not have really made the leap to
OOD, even though you are using an OOP language. I would encourage you to
read this:
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.
--
 
R

RichGK

Nick Malik said:
In other words, your message, and what small glimpse of your design that I
can glean from it, indicates that you may not have really made the leap to
OOD, even though you are using an OOP language. I would encourage you to
read this:
http://blogs.msdn.com/nickmalik/archive/2004/12/21/328727.aspx

Hi Nick,

I'm actually ok with OOD and previous web apps I have programmed all follow
the OOD principles, however I noticed that some of the classes I have
programmed in the past are there purely to enable connection to a database
and also return values from queries.

In these situations I was thinking that there seemed to be no gain from
having multiple intances created as they are not used in any kind of
relationship with other objects.

In the case of the parent class being abstract this is merely because there
is no reason to create an instance of it, it is there to be specialized via
inheritance.

I have to wonder why C# allows methods and data fields to be declared as
static, if then you are not supposed to do this as it is not strict OOD?

Cheers
Rich.
 
C

Cor Ligthert

RichGK.

Be aware that you have to use Static in a webform application and a winform
application completly different.

A webform application is a middle tier, while a winform is a UI tier.

Therefore a static class in a webform application belongs to all users,
while it does in a winform only belong to the special user of the winform.

Just as addition.

Cor
 
N

Nick Malik [Microsoft]

Hi Rich,
I'm actually ok with OOD and previous web apps I have programmed all
follow
the OOD principles

I accept that you say this, but I wonder if you have really made the leap.
Can you tell me which design patterns are informing your design of this part
of your application?
I noticed that some of the classes I have
programmed in the past are there purely to enable connection to a database
and also return values from queries.

In these situations I was thinking that there seemed to be no gain from
having multiple intances created as they are not used in any kind of
relationship with other objects.

Granted. I have seen this on occasion as well. However, the fact that
these classes don't contain dynamic contents in their state doesn't mean
that you don't benefit from defining them as objects. You created an
abstract base class, so clearly you feel that you can create common,
reusable code.

If the only thing different between your classes is data, then don't
inherit. Instantiate. Change your base class to a concrete type, and pass
the data to a instance in the constructor. E.g. use the classes as simple
instances of a single class.
I have to wonder why C# allows methods and data fields to be declared as
static, if then you are not supposed to do this as it is not strict OOD?

Static is useful, but not to be taken lightly. Using static in OO is like
using global variables in VB6. You can do it, and many times you should,
but you should always do it with forethought.

--
--- 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.
--
 
J

Jon Skeet [C# MVP]

Cor Ligthert said:
Be aware that you have to use Static in a webform application and a winform
application completly different.

I disagree with this - see the last paragraph.
A webform application is a middle tier, while a winform is a UI tier.

No, the web forms themselves (and presentation logic in the code-
behind) are form the UI tier. The middle tier can be either web
services underneath the UI tier, or code called by the UI tier.
Claiming the whole of a web form application is "middle tier" is wrong
IMO.
Therefore a static class in a webform application belongs to all users,
while it does in a winform only belong to the special user of the winform.

In both cases though, you really just need to think "is this applicable
to one particular instance of the type, or is it applicable to the type
in general".
 
K

k

Can you tell me which design patterns are informing your design of
this part
of your application?

I must say

a) Formal named patterns are not the be-all and end all of good OOD
(not that you explicitly said they were, but it seemed implict in your
remark).

b) It is not necessary to know the name of a pattern to be using it. I
know a few long time programmers (including myself) that seem to have
independently produced (and used) reusable design elements with no
formal exposure to patterns. I'm not the only one who, when finally
getting round to looking at the literature went through saying, 'yup',
'yup' 'been doing that one for years' (and similar things and
wondering) what all the fuss was about.

just my 2ps worth.

Also I'd be V. interested in what you (Nick) would recommend for
reading on OOD - there does seem to be stuff out there now, unlike the
last time I tried to find some (10 years ago - damn I'm getting old).
 
N

Nick Malik [Microsoft]

Also I'd be V. interested in what you (Nick) would recommend for
reading on OOD - there does seem to be stuff out there now, unlike the
last time I tried to find some (10 years ago - damn I'm getting old).

Check out the blog entry I posted earlier in this thread

--
--- 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.
--
 
B

Bruce Wood

Rich,

This has all been said here already, but perhaps not quite in this way.

The problem with your design is that there seems to be a conflict
between your choice to inherit and your choice to make the child
classes static. It's not static classes _per se_ that are getting you
the response you're getting. It's static classes that inherit from an
abstract base class. There are two reasons for this.

First, a static class in no way benefits from inheriting from anything.
It can't inherit methods, properties, fields, or events from its parent
class, because it can't be instantiated, and you can inherit only
non-static members.

Second, and to me this is the more important of the two objections: by
making the child classes static, you can't take advantage of
polymorphism. That is, you could never, now or in the future, create a
method that accepts simply a "DataAccess.TDG" as a parameter, and does
something with that object, regardless of whether it provides access to
employees, invoices, or purchase orders. That you can't see a need for
that now doesn't mean that a need will never arise, particularly as you
add more methods to your classes.

In short, declaring a class static assumes several things, in my
opinion:

1. (Trivially) that you will never need more than one of them.
2. That it doesn't need to fit anywhere in the inheritance hierarchy.
That is, a static class that inherits from another class should be
immediately suspect.
3. That you can't imagine ever needing to create variations on this
class... that is, inherit from it and create a new class with slightly
different behaviour. What about a ContractWorker class that is sort of
an Employee but sort of not?
4. That you can not imagine that this class will ever need to be used
polymorphically. This relates heavily to points #2 and #3, but is a
consideration all its own. Declaring a class static means that it can
never be passed as an argument to a method, and so can never be cast to
a base type, and so can never be used polymorphically.

Only if a class meets all four conditions should you think about making
it static. If a class meets the first condition alone (the reason that
many programmers incorrectly use static) then you should use the
Singleton pattern instead.
 
R

RichGK

Hi Rich,


I accept that you say this, but I wonder if you have really made the leap.
Can you tell me which design patterns are informing your design of this part
of your application?

Ah, now you've got me. It seem that this is later in the course I'm
studying! (M301 open university). Although I have been playing with OO for
a few years it takes some formal education to really cover all the nooks
and crannies (I feel).
Granted. I have seen this on occasion as well. However, the fact that
these classes don't contain dynamic contents in their state doesn't mean
that you don't benefit from defining them as objects. You created an
abstract base class, so clearly you feel that you can create common,
reusable code.

Ok I think see what your saying. Just because in this instance I don't need
re-usable code doen't mean to say that I won't ever require it in the
future?

And if I have constructed the classes this way I'll simply end up
re-programming it at some point rather than being able to inherit from it
if I then require the subclass to have multiple instances?
If the only thing different between your classes is data, then don't
inherit. Instantiate. Change your base class to a concrete type, and pass
the data to a instance in the constructor. E.g. use the classes as simple
instances of a single class.

Ok, I'll do that.
Static is useful, but not to be taken lightly. Using static in OO is like
using global variables in VB6. You can do it, and many times you should,
but you should always do it with forethought.

Thanks for your advice!
Rich.
 
J

Joanna Carter \(TeamB\)

Ok I think see what your saying. Just because in this instance I don't need
re-usable code doen't mean to say that I won't ever require it in the
future?

And if I have constructed the classes this way I'll simply end up
re-programming it at some point rather than being able to inherit from it
if I then require the subclass to have multiple instances?

You do realise that the static keyword has nothing to do with inheritance
and virtual methods, don't you?

It is used to denote methods, fields and properties that can be used without
instantiating the class. This means you effectively have a Singleton, i.e. a
type of which there can only ever be one instance.

Also C# does not allow virtual static methods, therefore the only reason to
make your base classes abstract is to prevent people from instantiating
them, not forcing them to derive from them.

Joanna
 
R

RichGK

In short, declaring a class static assumes several things, in my
opinion:

1. (Trivially) that you will never need more than one of them.
2. That it doesn't need to fit anywhere in the inheritance hierarchy.
That is, a static class that inherits from another class should be
immediately suspect.
3. That you can't imagine ever needing to create variations on this
class... that is, inherit from it and create a new class with slightly
different behaviour. What about a ContractWorker class that is sort of
an Employee but sort of not?
4. That you can not imagine that this class will ever need to be used
polymorphically. This relates heavily to points #2 and #3, but is a
consideration all its own. Declaring a class static means that it can
never be passed as an argument to a method, and so can never be cast to
a base type, and so can never be used polymorphically.

Only if a class meets all four conditions should you think about making
it static. If a class meets the first condition alone (the reason that
many programmers incorrectly use static) then you should use the
Singleton pattern instead.

Thanks Bruce, it is indeed the first condition that lead me to think it
would be suitable.

Luckily I booked it all into source safe before messing with this new idea!

Rich.
 
R

RichGK

You do realise that the static keyword has nothing to do with inheritance
and virtual methods, don't you?

It is used to denote methods, fields and properties that can be used without
instantiating the class. This means you effectively have a Singleton, i.e. a
type of which there can only ever be one instance.

Also C# does not allow virtual static methods, therefore the only reason to
make your base classes abstract is to prevent people from instantiating
them, not forcing them to derive from them.

Joanna

Could you give me an example of where it is suitable to use a static
method? (Apart from main() ;) )
 
J

Joanna Carter \(TeamB\)

Could you give me an example of where it is suitable to use a static
method? (Apart from main() ;) )

If you look at the Math framework class you will see that most of the
methods are called without creating an instance simply by calling e.g.
Math.Abs(...).

This is because all the data that is needed for an operation is passed into
the method; there is no need to create somewhere to store any of the
information to be operated on.

A different use for static classes is to ensure that only one instance is
ever available, but without having to create that single instance explicitly
in code.

I use this idea for my OPF (Object Persistence Framework). The idea is that
there is only ever one Object Store, which always has to exist from startup
to closedown of the app.

//.NET 1.1
public abstract class ObjectStore
{
private ObjectStore() {}
////
//.NET2.0
public static class ObjectStore
{
////
private static ConnectionList connections = new ConnectionList();

private static Connection activeConnection = null;

public static void SetActiveConnection(string name)
{
activeConnection = connections[name];
}

public static void AddConnection(string name, string dbType, string path,
string fileName)
{
if ( ! connections.Contains(name) )
{
Connection newConnection = ConnectionFactory.CreateConnection(name,
dbType, path, fileName);

connections.Add(newConnection);

if (activeConnection == null)
activeConnection = newConnection;
}
}

public static void Store(object obj)
{
activeConnection.Store(obj);
}

...
}

This can then be called like this :

{
ObjectStore.AddConnection("OracleAccounts",
"Oracle","C\Data","AccountsDB");

Customer cust = new Customer();

cust.Name = "Joanna";

ObjectStore.Store(cust);
}

But as Bruce says, this kind of use has to take into account that you can
never derive from this kind of class, so it has to be pretty much correctly
defined and tested before you let it into a production environment.

The main use for static classes is for the kind of scenario like my call to
ConnectionFactory. This follows the Class Factory pattern where, once again,
you only ever need one source that you don't want to bother instantiating.

The Singleton pattern that Bruce mentions is actually a specialised Class
Factory that only knows how to return and maintain a single instance of its
type. For those times when you really need a true single instance that you
can derive from, not just a static class.

Joanna
 
M

Mark Rae

My question is, is this ok?

I have something similar for interfacing with SQL Server where all the
methods are static, for no other reason than I don't need them to be
otherwise. I also have other classes with static methods e.g. for Registry
manipulation, mail integration, encryption, validation etc...

That's also pretty close to how Microsoft themselves do it in their Data
Access Application Blocks...
http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp

Also, have you had a look at this...?
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daag.asp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top