Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't static members make classes kind of (global) objects themselves?

Every time I come across an implementation of the singleton pattern or any static classes (i.e. classes with (almost) only static members) I wonder whether this isn't actually a hack and therefore heavy abuse of the principle of classes and instances just to design single objects instead of designing classes and creating a single instance. To me, it looks like static members of classes in general try to add some sort of characteristics to classes which they actually aren't supposed to have and which rather make them object themselves.

But is it really desirable to have single objects implemented like that? Or do you see things completely differently and don't think that such static classes or singletons have anything in common with actual objects?

like image 530
balu Avatar asked Dec 18 '22 09:12

balu


1 Answers

Static members are effectively just namespacing for globals, yes. Nothing wrong with that; namespacing is good, and globals are the cleanest way to accomplish some tasks.

Singletons can be somewhat more interesting (load on demand...) but they're a similar construct (yeah, you could think of a static member as an anonymous singleton managed by the compiler).

Like most things, these tools have their place, and only the ideologues worry about whether or not they "fit" with a particular ideology.

like image 188
Shog9 Avatar answered May 10 '23 19:05

Shog9