Bad Tip Of The Day
Looking at the list of tips, I came across a strange title that caused me to stop for a moment: "Access a Class Member Function without Creating a Class Object". My first reaction was that this was impossible. Then I remembered that in C++ almost nothing is impossible, so I opened the link. It seems like, as the title clearly suggest, there are cases in which you can call an instance method without creating an instance of the class. This is a valid scenario from a C++ perspective in cases where the method you call does not use any data members of the class. Such code will compile (which is not very surprising) but it will also run! Nice trick….
Or isn’t it? Apart from making no sense at all from a design perspective, such code is extremely dangerous and error prone. During the evolution of the target class, someone might change the target method such that it will use some data members. Needless to say that such a change will cause the client of this class (which used this method without creating an instance because the developer wanted to show what he knows) to crash.
Following this tip makes the client of the target method highly dependant in the way the method is implemented. This breaks all encapsulation and causes every change in the method to have an acute ripple effect over the entire code. Thus, what was originally presented as a C++ Tip, turned out to be a maintenance nightmare and a very fragile piece of code. In other words this tip is in fact a bad coding practice. Period.
So, what are the lessons from this short story? The first lesson is not to take everything anyone says for granted (I guess that also includes this article ;). The fact that this coding style was labeled as a tip does not automatically suggest that it is a good practice. The Web is filled with tips, tricks, guidelines and suggestions. You should adopt them advisedly after considering them appropriately.
The second lesson is as important: do not use any esoteric feature a programming language, a compiler, a platform or a technology provides you with. You should always consider the implications of using such a feature. The fact that something is possible does not automatically make it a good idea to use. Many “powerful” features are in fact dangerous because they are too unstable and error prone. The less you take “advantage” of such unconventional features, the more robust your code is.
Just in case you are curious, here is a link to the mentioned C++ “Tip”.











