C# Class Design

Hi,

I am trying to create a class library. The idea is that it will be the class that takes care of the connections to my database & retrieving or writing data to the database.

In the code example below I have a class called Prices in the namespace Securities & two other classes called WriteToDataBase & Retrieve in the namespace Results.

These classes will all do their separate things. They will all need to open and close an connection to the database. I do not want to have to write code in every class to open and close a connection to a the database. What be the best way to go about solving this?

Thanks,
M


namespace TradingDatabase
{
    class ConnectionHandler
    {
        public SqlConnection connection;
        public void Open()
        {
        }
        public void Close()
        {
        }
    }

    namespace Securities
    {
        public class Prices
        {                        
        }        
    }

    namespace Results
    {
        public class WriteToDataBase
        {
        }

        public class Retrieve
        {
        }
    }
}

Open in new window

mcs26Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
How about something like this with inheritance so the common code is in a base class
class X
{
  protected  SqlConnection connection;
        public void Open()
        {
        }
        public void Close()
        {
        }
}

class Y : X
{
  public foo()
  {
  Open();
  //do something();
  Close();
  }
 
 
}
0
Jacques Bourgeois (James Burger)PresidentCommented:
I would not create a namespace for each class. Since they are all part of the same "package", you should have a common namespace for the whole thing. That is the intention behind a namespace: to group together related features.

If System.IO or System.Data.SqlClient were split in many little namespaces, we would never be able to easily find the classes related to files and directories and those related to working with Sql Server.

And I would not go for inheritance. One of the first things you learn when you learn about about inheritance is the "Is a" rule. Is Y a X? Is Label a Control? If so, inheritance might be a good thing.

You inherit from something that you want to extend, not from something because it has a couple of methods that you need. Would it make sense if Bitmap inherited from System.IO.FileInfo just because you need a file to create a Bitmap?

It might not show up when things are simples as they are right now, but when the classes develop, you end up with strange stuff. You would end up with something that is bloated, makes no sense and is hard to use and maintain.

I would rather go for static members:
class ConnectionHandler
{
	public static SqlConnection connection;
	public static void Open ( )
		{
		}
	public static void Close ( )
		{
		}
}

Open in new window

Static members can be called directly on the class, without having to instantiate a variable:
ConnectionHandler.Open();

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AndyAinscowFreelance programmer / ConsultantCommented:
Hmm, considering a class is to be called eg. WriteToDatabase I find it odd you do not recommend inheritance.

Anyway - make certain you understand what static means and what effect it can have on your code.  If you don't be prepared for problems.
0
Jacques Bourgeois (James Burger)PresidentCommented:
Good point Andy. It was very late for me when I answered, and I should have gone a little further and complete my answer. A sentence such as "These classes will all do their separate things" should have triggered a more complete explanation.

You do not create a class to do different things. You create a class because you want to group related operations into one object that is dependant upon these operations.

Classes named WriteToDataBase and Retrieve are not good things. Look in the framework, and try to find a class name that is a verb. You do not create a class to perform only one operation. A verb like WriteToDataBase and Retrieve usually shows the need for a method, not for a class.

The role of a class is to accumulate a set of related data in a single entity, along with the operations (methods) needed to manipulate that data.

If you want only a collection of methods, you use a static class, such as System.IO.File.

And one can question the need to create a generic class to perform these operations. Writing and retrieving data to and from a database can be very different from one operation or table to another. Each requires different SQL or stored procedure, different parameters. And classes to work with these already exist in the framework. So why reinvent the wheel.

And since the recommended way to go for most operations is to use a local Connection variable, opening and closing in 2 different methods is not a very good idea either. The way to go, for most situations would look more something like the following:
namespace TradingDatabase
	{
	class ConnectionHandler
		{
		public static SqlConnection CreateConnection ( )
			{
			SqlConnection con=new SqlConnection("connectionString");
			// Code to create the connection
			return con;
			}
		}

		public class TradingItem
		{
			public void GetPrices ( )
			{
			SqlCommand cmd = new SqlCommand ( "command", ConnectionHandler.CreateConnection ( ) );
			// Prepare the command: SQL or stored procedure, parameters
			cmd.Connection.Open ( );
			cmd.ExecuteReader ( ); // Or any other Execute suited for the task
			// Retrieve the information in a format that is suitable for the application, such as filling the current class properties
			cmd.Connection.Close ( );
			}
		}
	}

Open in new window

As you can see, Open and Close already exist. What would you gain by creating your own? The line where we ExecuteReader plays the role of Retrieve, and it also already exists in the framework. In the same way, similar code with ExecuteNonQuery would WriteToDatabase.

The code in the 2 comment lines would be different for each operation, so you would need to write it anyway before calling your own methods, that would only call the already existing Open, Close, ExecuteReader and ExecuteNonQuery in the background.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.