Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Static members frowned upon? If so, why?

Status
Not open for further replies.

keyser456

IS-IT--Management
Nov 21, 2003
73
US
I'm implementing a data access layer for the project I'm currently working on. In order to provide basic validation these classes are each keeping track of the schemas for each of their fields (FieldName, Type, Size, Nullable).

I'm considering the use of static schemas so all this information doesn't have to be created for each and every instance of a record, however I've been told to avoid static members whenever possible. Why shouldn't I use static members, what are my alternatives, and what makes these alternatives better?

It seems to me avoiding the use of static members is wasting a very powerful and convenient feature, one that most programming languages seem to allow.

Thanks!
 
My speculation is that with static members, you lose the ability to use inheritance to override or extend functionality. This is more of an issue with methods, than with member data. With a static method you are stuck with the implementation you used in the base class (unless it's shadowed using "new" in C#), which could get really confusing and buggy.

It sounds like you are basically storing configuration data, so it makes sense to only have it in one place. Maybe a separate class that contains this data, but keep a singleton instance? This might free up the classes that use that data so they can vary independatly of the config stuff, via inheritance.

That's just one take on it, maybe others who can expand or provide a more correct answer...

Greetings,
Dragonwell
 
Static data gets a bad name because it encourages bad styles, like using it as an easily-accessible global bucket for data you don't have a proper home for (I've seen at least one VB developer book actually advising this as a way of working!). As long as you use it for it's intended purpose, static data can be useful. If you are going to use it, make it private.

Are you going to code these schemas/validators by hand? Or are you going to generate them from the database schema? If the former, you might consider using a singleton as dragonwell suggests, perhaps with some kind of dictionary pattern based on a hash collection. This can be populated on the first constructor call, maybe from the DB schema or an XML config file. There are relatively few SQL data types, so you could even hand off validation of each type to a helper class based on the result of the dictionary lookup.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top