Friday, February 6, 2009

Cool Programming Tricks Episode 2: Anonymous structs

This is a C++ trick that I learned at work. Similar concepts must exist in other languages, but I do not know of any. Additionally, this won't do much for EMACS or vi users who don't have auto-completion. How do you live by the way?

Anyway. You may be used to viewing structs as an inferior form of a class. Actually, they're technically the same in C++ with visibility differences, but in practice they are totally different! A struct is made for organization. Try thinking of them as tables inside a document, with several fields apiece that you can change separately. The uses of such might seem limited in programming, where you want to cut down on the amount of variables in each scope to simplify your efforts ( i.e., a new class with private variables. ) However, you will always wind up having a lot of things to choose from regardless of this simplification. Sometimes making a class to hold your many variables is not the answer. After all, what's the point of a class that's all accessors and mutators?

My sorting trick is an anonymous struct. I didn't even know these existed. They wear no type name, therefore you cannot instantiate it, ever. It exists once and only once: in the scope it's created in. Take a look:

class Game {
private:
struct {
BITMAP* player;
BITMAP* enemy;
BITMAP* background;
} graphics;

struct {
SOUND* music;
SOUND* hit;
} sfx;
}


These structs, graphics and sfx, ONLY exist inside this class. So they become like folders of data, and thanks to the power of IDEs, you can take advantage of this. For example, if you start designing a level for this game, you need to remember what the bad guy's BITMAP pointer was. Well you don't have to go to the header if you remembered 'graphics'. Simply type "graphics."(with the dot) and any IDE worth ten cents will pop up a box listing each of the images. If you don't want to have to memorize all these structs, put THEM in a struct called "media", and remember that. It's just like managing your desktop. You could take this really far and have every single one of your classes put all its private data in an anonymous struct called 'pdata', and never look through your headers again. A real time saver!

I do this frequently since learning at work. No problems so far. Do let me know what you think!

No comments: