May 2nd, 2013, 03:47 PM
When to use static classes
I am just wondering what the best practice is for when to use static classes (by static class, I mean a class which has only static attributes and functions).
If you are creating more than one independent object of a particular class, then obviously this should not be static because each object will be the same. But what about the case when you know that you will only ever need one instance of a class? On its own, does this mean that you should create it as a static class?
Personally, I use static class when I want its member attributes and functions to be available globally, which I think is fine. However, I am not sure about the case when I know that only one object will be created - should this be a static class or not?
May 3rd, 2013, 01:23 AM
Re: When to use static classes
The general consensus is as little as possible. The idea is that global shared data is bad because it induces dependencies in designs.
Originally Posted by karnavor
Nevertheless, there's a design pattern to handle the one global object situation and it's called the Singleton. Many have taken the very existence of Singleton as cue to use it extensively but design pattern or not, global data still is global data and it's better to avoid it.
On the other hand if you have a bunch of stateless global functions that belong together logically, of course you can make them static and keep them in a class. That's what you would do in Java (see for example the Math class). In C++ you can as well use free functions in a namespace.
Last edited by nuzzle; May 3rd, 2013 at 01:52 AM.
Click Here to Expand Forum to Full Width