Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Database-Class static?

I'm currently having a Class named "SqlData", which contains all the Methods needed to Connect to my MS-SQL Database.

It contains methods for Inserting, Deleting and Updating different kinds of tables - and therefore is used in many Windows of my WPF application.

Let's say that nearly 90% of my WPF-Windows are calling at least three Methods of my SqlData Methods for Loading, Inserting and Updating different records...

At the moment, I need to instantiate my Sql-Class in every Window - therefore I'm thinking of making the entire Class static so I don't need to instantiate it every time?

But also I've read not to use static classes while communicating with external Servers like WebServices or Databases.

Could you give me any advice on how I should go on?

Following a few Methods used in my Class (bool returns true, when the statement completed, otherwise false):

public DataTable GetAllSomething(DataTable _data)

public bool WriteSomething(Object something, out int insertedId)

public bool DeleteSomething(Object something)

Thank you!

like image 237
SeToY Avatar asked Sep 12 '11 12:09

SeToY


People also ask

Can base class be static?

No, It's not possible to inherit Static class.

How do you create a static class?

We can declare a class static by using the static keyword. A class can be declared static only if it is a nested class. It does not require any reference of the outer class. The property of the static class is that it does not allows us to access the non-static members of the outer class.

What is a static class?

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type.

Can we create static class in PHP?

In PHP, we can have both static as well as non-static (instantiated) classes. Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both.


1 Answers

At the moment, I need to instantiate my Sql-Class in every Window - therefore I'm thinking of making the entire Class static so I don't need to instantiate it every time?

The time taken to instantiate a class in .NET is so ridiculously low that you should not be worried about. Personally I don't use static classes because they introduce strong coupling between the different layers of an application making them more difficult to unit test in isolation.

So I prefer to abstract all database access behind an interface (or abstract class) and then provide an implementation of this interface against a specific database.

like image 101
Darin Dimitrov Avatar answered Oct 21 '22 11:10

Darin Dimitrov