A couple of questions re static classes. Some of this is from stuff I have read a while ago so I want to dispell any myths.
I know that if I need one instance of a class, eg like to represent one company (ie company details), the class can be static. Why do I need multiple identical instances?
However:
1) Can the choice of parameters in the methods of a class (ie the type or whether its an instance class/interface etc) , instance or otherwise, affect the decision to make a class static or not? So if I provide an instance object as a parameter (e.g. myMethod(new Car()) ), or anything, can this have any influence on whether to make the class static or not? I read a while back that this can, so I am trying to dispell a myth.
2) If the static class does not use another class's state, does this have any bearing on making a class static?
IE a static class which contains a field, and that field is used within the class's ownn methods.
I also read a post on here about static and a member said that if the class does not contain "repeatable" functionality, it could be made static. What does repeatable mean in this context?
Thanks
In sum, make the method (or class) static if it will never consume or modify state on its own instance. In other words, if it doesn't make use of this (either explicitly or implied) then it should probably be made static.
Three reasons to make an object not static:
Your object will need to be set to a newly initialized state more than once. You could write a method to do the reinitialization, but Note that although static classes can have a constructor (which I believe is not called until the first reference to a member of the static class triggers the class to be loaded), you can't call it run-time.
You might want to have a 'memento' copy of the object to undo to when the user cancels editing a 'work' copy.
The static object might be accessed from multiple instantiated objects at the same time. I have seen problems from an ASP.NET web application where a static object was used to store user and state data during page load processing that would have been shared between simultaneous page requests from different users.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With