Skip to content

Use of casts in the Plasma code

Friday, 21 November 2008  |  richard dale

Recently I've often been amazed by the ingenuity and the lengths that some people seem to want to go to, in order to be rude about KDE4. One example was a guy on Aaron's blog about the new system tray who claimed that Plasma had 'too many casts' especially dynamic_casts. 'Hey what? Huh?' I thought, as it was a bit off the wall.

However, we have all got the Plasma sources right there in the kdelibs trunk module, and so this morning I thought I'd do a quick survey to see if there was any truth in Ramsees' claims.

Firstly, how many dynamic_casts are there in the Plasma libs code?

mardigras rdale 57% cd kdelibs/plasma
mardigras rdale 58% find . -name "*.cpp" -exec grep dynamic_cast {} \; | wc -l
21

Which sources?

mardigras rdale 59% find . -name "*.cpp" -exec grep -l dynamic_cast {} \;
./applet.cpp
./popupapplet.cpp
./extenderitem.cpp
./extender.cpp
./corona.cpp
./tooltipmanager.cpp
./containment.cpp
./private/toolbox.cpp
./animator.cpp

So we have 21 casts in 9 different C++ source files. Aaron's blog currently has 111 comments, and so there are five times as many comments as there are casts. In fact, we probably have almost as many comments about casts as there were casts.

I counted many lines are in the Plasma .cpp and .h files including white space and comments. As there are about 40000, it means that we have one dynamic_cast for every 2000 lines of code. If you are familiar with the QGraphicsView api that Plasma uses as a canvas to draw on, you will know that it has quite a complicated class structure with multiple inheritance, and quite complicated interactions with the standard QObject/QWidget classes. I would say that it is pretty much impossible to use it without doing any casts and that we can say with quite a lot of certainty that 21 casts in Plasma is a very reasonable figure.

I counted the static_casts and found 101, which again is pretty much what you would expect given a C++ library of this size and complexity.

OK, there you have it then - I am happy to confirm that the Plasma code is well written and well designed from the point of view of cast usage.