I am not too familiar with classes and stuff so I am asking for some simple help here.. I’ve got a lot of database functions which I use a lot so I thought I’d put this into a class which I can call from other classes which require data from the database.
For example I’ve got a window that outputs a list of people, I’ve got the same code in the edit person window and I am repeating the same code for both of them.
What class to a I use ? I am very confused. I’ve implemented it as a static class but I wasn’t sure if it was working correctly.
If someone could just give a simple primer on what classes are which I would very much appreciate it.
Thanks
A static class is basically a dressed up global variable. You don’t create instances of a static class. All the methods must be static and if it holds onto any data, the data fields must be static. This means that all code that uses this class will be using the same data.
If your intent is to centralize db access pain points like login and session, a static class might be appropriate. Just always keep in mind that calls from different clients will see the same details from the static class.
A non-static class, or instance, is something that stores different data in each instance. You have to create an object instance of the class before you can do anything with it. The advantage of creating an object is that each consumer that constructs its own instance is isolated from any other consumers of that class. If window A constructs an instance of your db class and does operation abc, and window B constructs its own instance of your db class and does operation xyz, abc and xyz will not cross paths – they do not share any data between them.
In general, object instances are usually preferred over global/static classes because the shared nature of static classes creates data dependencies and side effects that the consumer may not be aware of.