Making Database-Class static? - c#

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!

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.

Just do not do it, it's ok to create an instance of your class every time it is needed, there is nothing wrong with that.
even if you are not doing it yet right now, you could imagine to use some kind of Dependency Injection soon in the future, or you could write unit tests with any testing framework available in .NET and in general you will have much more options with no static classes.

I always create a database object at the beginning of my app and pass it with the constructors of all windows and classes which need it. It gives me the ability to add data to it, like a connectionstring, which is only needed in the beginning, and there's not a chance methods are being called before the databaseconnection has been set up (as can be with static) because that's done in the constructor.

Related

Interface vs instance of class

My application has a BusinessLogic layer which calls out to a DatabaseAccessLayer, which contains a static class for CRUD operations. It opens a connection to my database, performs the update then returns (it doesn't store anything individually).
The problem comes when my endpoint needs to control the database that its writing to (TEST1, TEST2, DEV, etc). I need to pass in a connection string into the static class.
I am struggling to understand why an interface is better than using a direct instance of a class or vice versa, or indeed if there is another preferred method (I read a post about using delegates but this seems old fashioned to me).
I have tried writing an interface, implement it in the DatabaseAccessLayer but how do I call that from my business logic layer? I don't care what the code is in the DAL at the BL point, I just want it to call that code. But it seems if I implement it, I have to implement all the methods (what code goes in there!). And I understand that you can't declare an instance of the Interface and call the methods.
Can anybody suggest an approach? Is using an instance of a class sufficient?
I think you mix two rather distinct things, the Interface and the Instance of a Class.
In very simple words:
An interface is like a contract - All the classes that will
implement it must implement its methods
An instance is like ...
an Instance of a Class - i.e. an object made
according to a blueprint
Regarding your problem with various connections, now, this is another, I believe irrelevant problem. Your class is static, OK, that means you may not create an instance of it. You use it directly by calling its methods. You can always pass a connection string as a parameter to any of its methods. In fact that is what I suggest as a solution to your question:
pass a connection string as a parameter to any of its methods
Edit: Now that I see your question again... you might have faced problems with the Static Class member fields, IF you have the connection string as a field of your Static Class! Beware that fields of static classes are shared, meaning that, if changed by ANY of the endpoints using the class, they are changed for ALL the rest endpoints that will use the class. So, that might have caused you troubles...
In that case... again...
pass a connection string as a parameter to any of its methods
Edit2: No, that was wrong of me to suggest that you pass a conn String as a param to Data Layer!!! Data layer should have the connection string encapsulated (as an internal parameter). The consumers should not know the direction of the Data - whether it is DEV or PROD.

Utility classes: static class vs member variable vs local variable

I'm creating a utility class CommonDaoOperations that contains several generic methods: Create, Update, Delete.
This is not a base class because some DAOs are more complex and can't use these generic methods, but many DAOs can.
I'm now pondering how that utiliy class should look like exactly:
static class with only static generic methods
regular class with generic methods, created once per DAO as private readonly member
regular class with generic methods, created once per DAO method (in each call)
Creating an instance of a class per DAO / method obviously costs more than calling a static method, but I'm pretty sure that these costs are negligable in almost any application.
I'd favor solution 2 or 3 because of the benefits of non-static classes (interfaces, can be mocked, can be derived / enhanced, could gather parameters via constructor in the future should it be necessary (compared to a 10-parameter-method in a static class)).
So I guess the real question is: should I be creating my utility class as a member variable, or instantiate it per DAO method?
public void Create(User user) {
new CommonDaoOperations().Create(user);
}
public void Delete(User user) {
var daoOps = new CommonDaoOperations();
daoOps.CheckSomething(); // just an example of multiple calls to the class
daoOps.Delete(user);
}
I'm interested to hear what other devs think about any of these approaches, or if there's still anothere / better way to do this.
Edit
Just realized that I should have given approach #3 more thought - as Vadim pointed out, replacing the concrete class would be cumbersome when it's instantiated in each method, but I could factor that in a property:
private CommonDaoOperations DaoOps {
get { return new CommonDaoOperations(); }
}
public void Create(User user) {
DaoOps.Create(user);
}
I believe this to be more maintianable than the above snippet, however know I introduced a property for a 'utility' class in my DAO, which might be a code smell by itself (as Ant P pointed out).
Summary
This was a tough decision - while I accepted the answer from Ant P, Vadim's answer is also legitimate. Which approach to use depends on the utility class, all 3 approaches have their uses (except the updated #3). At least that is my take of the provided answers.
Static classes do have their uses, but also many downsides as briefly mentioned above.
Regular class, instantiated per method: the utiliy class is created and used just where it is required. Reduces dependencies, keeps your type pure.
Regular class, instantiated as member: when many/all methods require an instance of the utility class, it may be a better idea to create a member variable. Changing the type or how it is instantiated becomes easier this way.
I will let those more qualified comment on the performance implications; however, here are my thoughts on each:
1. Static class
This concept is fine for simple, 'uncomprehensive' utility methods that require no real extensibility but - as you note yourself - your common DAO operations stand to grow considerably more sophisticated. This is unlikely to be very manageable as a single static class, particularly when it's used across multiple different types of DAO.
2. Concrete class, instantiated per-DAO object
This is all fine and dandy, but do you really need the utility class to be a member of the individual DAO? I could understand this if you needed some kind of consistency or state persistence within the utility class, across the lifetime of the DAO, but it seems that these methods are fairly nebulous (true to its name as a "utility" class).
Which leaves 3. Concrete class, instantiated per method. This seems the most natural solution to me. This gives you the flexibility to make use of all of the advantages of a concrete class as you acknowledge in your question, while restricting the scope of the object to where it's needed - the individual method call.
Should your class evolve into something that's needed across the entire DAO, e.g. you suddenly need to maintain the state of the object (or if you need to inject it into the DAO's constructor, or something else along those lines), you can always change where it's instantiated (though it seems to me that, if this happens, you don't really have a utility class any more and you need to reconsider how this class fits into your architecture).
Unless you plan to create an exceptionally large number of these objects, I don't think it'll affect performance.
I would prefer (2). There's simply need to create it for each use, that's just writing code for nothing. In addition, if you'd ever want to use some sort of IOC, get the utility class as a parameter, change the way it is initialized or simply change the class to another class - having a single member to change is a lot easier than changing all the places where it's used.
Unless you have a very good reason, stay away from statics or Singletons. (an example of a very good reason is something like developing an addon or a plugin in which you don't control the way your classes are initialized and used).
When considering the difference and usages between static classes and concrete classes sure there are implications to take in mind, see the testability for example (but this is not so sure at all as shown after), but there are first of all, some assumptions to do:
instance classes have state, manage state, and behaviors are related to it's internal state, if operations are not related to internal state in some ways, these are truly candidates for static methods, but I will say more after about that. This is the base even for encapsulation, and goes hand by hand with SRP (Single Responsibility Principle) which says that a class should have a single responsibility, doing one thing and no more, so, this gives you the fact that methods are all related to it's internal state directly or indirectly
static classes haven't and don't manage state. Maybe some one could say that it's not true at all, see singletons. Well, singleton's maybe good, but singletons designed as static classes are too close to anti-pattern, in this case, singletons could be managed as IoC containers does, by managing justo one instance at all. If needed I could provide some examples about with and without containers.
Well, someone says static classes are something close to anti-pattern, because for example testability.. well, this is non true, and this depends of what the static class and test which involves to is related.
I will report a very good example on that by on of the great software architect at all, Udi Dahan, which for example, in a good article about Domain Events, he talks between other things, about static classes and testability, here the link Domain Events Salvation if you go to the section How to raise domain events and Unit testing with domain events, he talks about that.
After that, as you says, another difference about the two, is about memory cost, but others says about that. Take in mind that, tools like Reshaper, makes suggestions to transform instance classes/methods which doesn't handle state to the static representation, this in advantage of memory and usage.
The last words about your design: CommonDaoOperations seems to a truly static class which doesn't handle state, so it's a good candidate to be a static class, for it's nature, for jobs it does. You can instead treat it as "singleton" using a IoC container and configuring that class in the right way. There are many ways to accomplish that in other ways without Containers.. here a simple article which talks about singletons and static classes C# Singleton, Static Class. Sure making a property which returns the helper is not so a good design, and a property which returns a new instance for a get operation is always a bad design, it will be justified with solid reasons...
So seeing your design and how you use the helper class, the words says by Udi in the link above describe well the solution you should implement.

When to go for static classes?

Whenever I code a solution to something I tend to either use a lot of static classes or none at all. For example in a recent project I had to send a class with some string/bool/datetime data through a number of hoops and the only thing that wasn't static was this data-holding class. Everything else (3 pretty hefty classes with different processing responsibilities) were static.
I think what I'm asking for here is some input on when (and why) I should avoid using static classes for these "process X, output Y" cases. Is it ok to always use them as long as they work or am I shooting myself in the foot concerning scalability, plugin-support etc?
I hope this is an OK question to ask here. I'm not asking for an argument concerning whether or not static classes are "better" - just input on when I should avoid using them.
Most of the code i write:
Uses dependency injection/IoC
And needs to be mockable/testable
So i just use objects for almost everything.
I do still use statics for things like:
Extension methods
Constants
Helper/Utility methods (pre extension methods)
operator methods
Still the two questions remain a bit the same. My main concern on static classes is inheritance and accessability.
When using a static class (public in the worst case), everyone is able to access your processes and functions. Which is most of the time not what you want. It is too easy for some object to get to your functions and do some modifications. Therefore, dependency injection is nice to use. (Pass the object you want to modify in the parameters, which is in this case your process-object).
To prevent others from manipulating your process-object, why not try to use some kind of singleton pattern (or even an ex-singleton pattern), so there is actually a real object to talk to? You can pass the object into the parameters of your functions if something should be modified. And then you can just have one manager that holds your process-object. Others shouldn't get to the object.
Static classes are also hard to inherit. Overriding static methods seems a bit strange. So if you are sure that the process will not be the only process, and some more specific processes will be created by you, then a static class should be avoided as well.
Static classes are commonly used for small data containers and general methods. It should not contain large data until unless required. These classes are non-extensible.
I would recommend you to have a method as static if it has only one method. In this case creating an instance of the class hardly makes sense
You can have static properties in case you want a field to act somewhat like global variable. This is a design pattern which matches Singleton pattern
I use static properties for tracking state which needs to be consumed by the whole application.
For rest everything related to my work objects is the way to go (with minor exceptions obviously)
Making extensive use of statics is like puting your application into concrete. They should be avoided except for very particular situations like utility/helper methods that are very general. A nice list was posted in a previous answer by djeeg.
The main problem I see with using static classes as you describe is that the dependencies are hardwired. If class A needs to use features from class B, it must explicitly know about it, which results in tight coupling.
While this is not always a problem, as your code grows you might find it more difficult to alter the behavior of the program to accommodate new requirements. For example, if you want to make the behavior of the program configurable, it will be difficult because that will require explicit if / switch in the code. Otherwise, you could simply make a class depend on an interface and swap implementations.
In short, you are preventing yourself from using well known design patterns that are known good solutions to solve issues you will likely encounter.
I usually try to avoid using static methods in classes. If I need to access some data globally I would at least wrap a class in a singleton. For larger projects I would recommend using an Inversion of Control container to instantiate and inject your "global" instances in a Singleton way.

Why choose a static class over a singleton implementation?

The Static Vs. Singleton question has been discussed before many times in SO.
However, all the answers pointed out the many advantages of a singleton.
My question is - what are the advantages of a static class over a singleton?
Why not simply choose a singleton every time?
Static class is a technical tool in your box - basically a language feature.
Singleton is an architectural concept.
You may use a static class as a means to implement the singleton concept. Or you may use some other approach.
With static classes in C# there are two potential dangers if you're not careful.
The requested resources will not be freed until the end of application life
The values of static variables are shared within an application. Especially bad for ASP.NET applications, because these values will then be shared between all users of a site residing in a particular Application Domain.
From MSDN
Static classes and class members are used to create data and functions
that can be accessed without creating an instance of the class. Static
class members can be used to separate data and behavior that is
independent of any object identity: the data and functions do not
change regardless of what happens to the object. Static classes can be
used when there is no data or behavior in the class that depends on
object identity.
A key point is that static classes do not require an instance reference. Also note that static classes are specifically enabled by the language and compiler.
Singleton classes are just user coded classes implementing the Singleton design pattern. Singleton purpose is to restrict instantiation of an class to a single instance.
If you coded every static class as a singleton you'd have to instantiate the class every time you used it.
i.e.
Console.WriteLine('Hello World');
would become
Console c = Console.getInstance();
c.WriteLine('Hello World');
I'd say they're both (generally) poor solutions. There are a few use cases for static classes, primarily simple utility ones (Extension Methods in C# 3.0 come to mind). With any degree of complexity, though, testability issues start cropping up.
Say class A depends on static class B. You want to test class A in isolation. That's hard.
So you go with a Singleton. You have the same problem - class A depends on singleton B. You can't test class A in isolation.
When class B has other dependencies (such as hitting a database) or is mutable (other classes can change its global state), the problem is exacerbated.
IoC (Inversion of Control) container libraries are one solution to this problem; they let you define Plain Old Classes as having a long lifespan. When combined with a mocking library, they can make your code very testable.
Static classes are much easier to implement - I have seen many attempts at thread-safe singletons in C# that employs naive locking schemes instead of depending on the run-time's guaranteed one-time initialization of static fields (optionally inside a nested class to delay instantiation).
Other than that, I think singletons are great if you need to pass around a reference to an object that implements a specific interface, when that 'implemention' should be singleton, something which you cannot do with static classes.
One consideration I don't see mentioned is that preferring a solution using an instance of a class (singletons, or their DI equivalent) allows you to provide a class on which other users of your code may define extension methods -- since extension methods only work with non-static classes as the this parameter. In other words, if you have a line like:
GlobalSettings.SomeMethod();
Then syntactically the only thing that can be accessed via GlobalSettings are members you provide. In contrast, if GlobalSettings is an instance (singleton or otherwise) then consumers may add their own extensions to GlobalSettings that they would be unable to do otherwise:
application.GlobalSettings.CustomSomethingOrOther();
or
GlobalSettings.Instance.CustomSomethingOrOther();
The question leads to the need for a better understanding of what you are implementing, how it suppose to work, and what it should be capable of.
Let's say, you need some kind of Manager class that handles your object's in a particular way. Singleton requires a bit more work, but in return, it gives you the ability to treat your manager by its interface (IManager) rather than the strict name. With a static class, you obviously losing the inheritance, interfaces, and the ability to swap or reset the object by just re-instantiating it rather than manually zeroing all the static variables, but it also gets you rid of a bit of extra work in case if your static object is kept simple.
There are more extra details if you go deeper, but in general 99% of times, it's just a question of personal preference or your team's coding guidelines.

C# Console App Session/Storage

What would be the best way to implement a psuedo-session/local storage class in a console app? Basically, when the app starts I will take in some arguments that I want to make available to every class while the app is running. I was thinking I could just create a static class and init the values when the app starts, but is there a more elegant way?
I typically create a static class called 'ConfigurationCache' (or something of the sort) that can be used to provide application-wide configuration settings.
Keep in mind that you don't want to get too carried away with globals. I seriously recommend taking a look at your design and passing just what you need via method parameters. You're design should be such that each method receives a parameter for what is needed (see Code Complete 2 - Steve McConnell).
This isn't to say a static class is wrong but ask yourself why you need that over passing parameters into your various classes and methods.
If you want to take the command line arguments (or some other super-duper setting) and put them somewhere that your whole app can see, I don't know why you would consider it "inelegant" to put them in a static class when the app starts. That sounds exactly like what you want to do.
you could use the singleton design pattern if you need an object that you can pass around in your code but imo a static class is fine, too.
Frankly, I think the most elegant way would be to rethink your design to avoid "global" variables. Classes should be created or receive data they need to be constructed; methods should operate on those data. You violate encapsulation by making global variables that a class or classes need to do their jobs.
I would suggest possibly implementing a singleton class to manage your psuedo-session data. You'll have the ability to access the data globally while ensuring only one instance of the class exists and remains consistent while shared between your objects.
MSDN implementation of a singleton class
Think about your data as a configuration file required by all your classes. The file would be accessible from every class - so there is nothing really wrong with exposing the data through a static class.
But every class would have to know the path to the configuration file and a change of the path would affect many classes. (Of course, the path should better be a constant in only one class referenced by all classes riquiring the path.) So a better solution would be creating a class the encapsulates the access to the configuartion file. Now every class can create an instance of this class and access the configuartion data of the file. Because your data is not backed by a file, you would have to build something like a monostate.
Now you could start thinking about class coupling. Does it matter for you? Are you planning to write unit test and will you have to mock the configuration data? Yes? In this case you should start thinking about using dependency injection and accessing the data only through an interace.
So I suggest using dependency injection using an interface and I would implement the interface with the monostate pattern.

Categories