Tuesday, September 1, 2009

Lazily loading and generics

This is an advanced topic and is not necessarily related with NaroCAD (but I found this problem right now in NaroCAD codebase as I've did a refactor).

Just in case you are too much used with C++, or you've just setup your mindset to C++ way, I want to present a case I've met today and is pretty bad to find the problem in case you are not prepared with it.

In C++ the compiler/linker combination takes all global and static variables that are in a class and initialize them. This is great in singletons, so you can initialize singletons, or register a component (as does MFC in their macros to register windows and message mapped functions).

So let's consider the MFC case: you want to create a dialog via it's resource ID, which is an integer, and you know that is defined as a #define MAIN_DIALOG_ID 12314.

When you will do a CWnd *wnd = CreateWindowById(MAIN_DIALOG_ID); this code will mostly work just because in other C++, there is registered this MAIN_DIALOG_ID with a resource data enough to supply the dialog information.

In .NET, or in C# in particular, you can create classes that you want to register with their IDs and you will see that they are not registered.

Let's think to a DialogFactory that can register any ID based from your class that is derived from a particulary NaroWindowBase. Let's suppose that you create a class named ThisDiaog derived from NaroWindowBase. And to register it, you do somelike this: static bool toRegister = DialogFactory.Instance.Register(MAIN_DIALOG_ID);

Because toRegister is static, you would expect that by it's initializing to register your dialog, but this will not happen till you use in other class your ThisDialog. To register it, you should create an empty static method and to call it, or to do registering explicit. Or to use the type as Generic name out of context, but to use the type, and the registering will happen.

The good part is anyway this: in most cases you don't want to initialize static singletons that you don't ever use in your applications.

No comments: