none
Static versus Instanced Classes... for Dummies?

    Pregunta

  • Ok, I was hoping for a little "theory" help here...  I'm still trying to get a grasp on when to use an instanced class versus a static class.  I've done quite a bit of reading on it, but they always want to use examples like the "Car Class" or the "Animal Class" rather than something based on a real world business application.  I understand what the differences are, I'm just unsure about the need for an instance outside of a large multi-user or web based application.

    For example:  I'm working on a simple database application.  I would like to put all of my database routines (Connect, Read, Write, etc.) in a separate "Database Class."  The app will also import and export data from/to XML files, therefore I would like to put all of my XML file routines into a separate "XmlFile Class."  What I don't know is whether or not these should be Instance Classes, and if so why?  If it's a single user application, then there should never be more than one database or XML file operation happening at any given time... so why would I ever need more than one instance of those classes?

    I know my way of thinking has to be flawed, because I can't come up with a reason why I couldn't write the entire application using nothing but static classes.   

    Any help, advice, or insight would be greatly appreciated.

    Thanks in advanced!

    jueves, 05 de abril de 2012 2:42

Respuestas

  • Turbo, 

    In addition from what is already written. 

    A static class is fine if it contains only methods (a kind of helper class or extension). 

    As soon as your static class starts to contain data, you are mostly more time busy by verifying if the data is still actual, then simply instancing new objects; because of the latter OOP was born. 

    However, be aware that is no 100% rule, for instance in ASP.Net application where a static class belongs to all sessions (users) there are sometimes situations where that saves a lot of access.


    Success
    Cor


    jueves, 05 de abril de 2012 7:02
  • The class which deal with database - Connect, Read, Delete, Update, can all be inside a static class. There is not need to create an instance and talk to database(As through one instance we can achieve this)

    Now take an example of and Employee Management system. System manages employee details like Contact Information, Salary Details, Holidays etc. In this case we need multiple objects as each object depicts a single employee. Here we can't use static vs. we require an instance.


    A.m.a.L Hashim
    Microsoft Most Valuable Professional
    Dot Net Goodies

    jueves, 05 de abril de 2012 2:48
  • Generally, you'll want to lean toward instance classes.  Instance classes can be freed from memory.  Static classes will sit around until the program ends.  That can be a minor or a major issue.  There are a phelethora of other reasons that matter depending on your specific program.  For example, sharing your static class across different threads can get tricky; whereas, an instance can easily be made thread safe.

    jueves, 05 de abril de 2012 3:32
  • I'm with Cor here.  If you have a method that returns a value based on it's parameters and doesn't need to store any information between method calls to be useful (these are often termed Utility methods) it can make sense for a number of them to be grouped in a static class.  As soon as a method needs to store information between method calls, or if you find yourself wanting to pass the same parameter to a method lots of times, or to lots of different methods, then it's time to start asking yourself if it wouldn't make more sense for these methods to be in an instance that hold onto that 'parameter' you keep passing around.

    In reality though, most methods end up not being just utility methods, so you should 'default' to using instanced classes unless you have some compelling reason for the class/method to be static.

    "I know my way of thinking has to be flawed, because I can't come up with a reason why I couldn't write the entire application using nothing but static classes.   "

    You can do exactly that.  That's what programming in C is like; there are no objects in C, only methods and structs, and structs don't contain methods (in other words, every method is a static method).  It has a whole host of problems, which is why OOB came about.  That style of programming is applicable to certain contexts, though.  JavaScript, for example, can create objects and use them, but most programming in javascript is just writing global (effectively static) methods/variables and calling them directly or attaching them to events.  It's rather rare to actually build a real instanced object in Javascript.  It's mostly just frameworks and javascript code libraries that do that.  In that particular context it just makes sense.  (Mostly because the code is all so short/small; it's uncommon to have a very large javascript program.)

    jueves, 05 de abril de 2012 15:23

Todas las respuestas

  • The class which deal with database - Connect, Read, Delete, Update, can all be inside a static class. There is not need to create an instance and talk to database(As through one instance we can achieve this)

    Now take an example of and Employee Management system. System manages employee details like Contact Information, Salary Details, Holidays etc. In this case we need multiple objects as each object depicts a single employee. Here we can't use static vs. we require an instance.


    A.m.a.L Hashim
    Microsoft Most Valuable Professional
    Dot Net Goodies

    jueves, 05 de abril de 2012 2:48
  • Generally, you'll want to lean toward instance classes.  Instance classes can be freed from memory.  Static classes will sit around until the program ends.  That can be a minor or a major issue.  There are a phelethora of other reasons that matter depending on your specific program.  For example, sharing your static class across different threads can get tricky; whereas, an instance can easily be made thread safe.

    jueves, 05 de abril de 2012 3:32
  • Turbo, 

    In addition from what is already written. 

    A static class is fine if it contains only methods (a kind of helper class or extension). 

    As soon as your static class starts to contain data, you are mostly more time busy by verifying if the data is still actual, then simply instancing new objects; because of the latter OOP was born. 

    However, be aware that is no 100% rule, for instance in ASP.Net application where a static class belongs to all sessions (users) there are sometimes situations where that saves a lot of access.


    Success
    Cor


    jueves, 05 de abril de 2012 7:02
  • I'm with Cor here.  If you have a method that returns a value based on it's parameters and doesn't need to store any information between method calls to be useful (these are often termed Utility methods) it can make sense for a number of them to be grouped in a static class.  As soon as a method needs to store information between method calls, or if you find yourself wanting to pass the same parameter to a method lots of times, or to lots of different methods, then it's time to start asking yourself if it wouldn't make more sense for these methods to be in an instance that hold onto that 'parameter' you keep passing around.

    In reality though, most methods end up not being just utility methods, so you should 'default' to using instanced classes unless you have some compelling reason for the class/method to be static.

    "I know my way of thinking has to be flawed, because I can't come up with a reason why I couldn't write the entire application using nothing but static classes.   "

    You can do exactly that.  That's what programming in C is like; there are no objects in C, only methods and structs, and structs don't contain methods (in other words, every method is a static method).  It has a whole host of problems, which is why OOB came about.  That style of programming is applicable to certain contexts, though.  JavaScript, for example, can create objects and use them, but most programming in javascript is just writing global (effectively static) methods/variables and calling them directly or attaching them to events.  It's rather rare to actually build a real instanced object in Javascript.  It's mostly just frameworks and javascript code libraries that do that.  In that particular context it just makes sense.  (Mostly because the code is all so short/small; it's uncommon to have a very large javascript program.)

    jueves, 05 de abril de 2012 15:23
  • I appreciated all of the responses.

    So if I understand correctly, the advantages to making a class instanced are:

    • Performance benefit from being able to dispose of the object, so that it is not tying up memory when it is not being used.
    • Less code required to dispose and then create a new instance rather than update/overwite the old properties with new data.
    • Safer to dispose the instance and create a new instance rather than take a chance that old data somehow gets leftover.

    Is this more or less accurate?  And is it safe to assume that unless I have a really good reason otherwise, err on the side of making all classes instanced?

    Thanks again!

    jueves, 05 de abril de 2012 17:43
  • Not really.  The question is whether you have a 'state' or data this is being stored.  If you're storing data and you want that data to only exist once per application, and be accessible to basically everyone, then it would be static.  This is rarely good from a design perspective.

    An instance of a class on the other hand creates a group of variables for which groups can be created any number of times, and for which the scope of their use/visibility can be limited.

    Usually, if you're storing some sort of 'state' beyond the scope of a single method it should be a  method that's in an instanced class.  If a method has no 'state' that it uses at all, and only uses local variables, then you can just make that method static.

    jueves, 05 de abril de 2012 18:00
  • Yea that is in general right, as long as you don't mix it up with the Dispose method which is available in all most all form classes (inherited from Components). 

    That method is meant to release unmanaged resources and not to deconstruct the object itself which is of course impossible as a method from a Class.

    Therefore try to avoid the word Dispose because it has given endless confusions.


    Success
    Cor



    jueves, 05 de abril de 2012 18:11
  • Yea that is in general right, as long as you don't mix it up with the Dispose method which is available in all most form classes (inherited from Components). 

    That method is meant to release unmanaged resources and not to deconstruct the object itself which is of course impossible as a method from a Class.

    Therefore try to avoid the word Dispose because it has given endless confusions.


    Success
    Cor


    Then I am confused...  If I can't use a Dispose method, how do I "clean up" the instance of the class?   For example:  I have a class named Employee and I create an instance of that class named CurrentEmployee.  I use a set method to load data from a database record to the properties of that CurrentEmployee object.  Once I am done with that record and want to move on to the next, how do I get clean up that instance before loading the next record?

    Thanks again and my apologies for being so thick headed.

    jueves, 05 de abril de 2012 18:55
  • The Garbage Collector does it for you.  A LOT of time and effort has been spent into building a sophisticated algorithm for determining the best way to do it.  In other imperative languages, such as C or C++, you were responsible for destroying objects that you created.  If you failed to do so properly it resulted in a 'memory leak' or memory that is allocated but no longer used and never cleaned up.  It's one of the most prevalent bugs in non-trivial programs in those types of languages.  When people need to do it themselves they simply rarely do it right, at least consistently.

    jueves, 05 de abril de 2012 19:10