Angus Leeming wrote:
Richard Heck <[EMAIL PROTECTED]> writes:

This is very boring:

CommandInfo const * InsetCommandParams::findInfo(
    InsetCode code, std::string const & cmdName)
{
    switch (code) {
    case BIBITEM_CODE:
        return InsetBibitem::findInfo(cmdName);
    case BIBTEX_CODE:
        return InsetBibtex::findInfo(cmdName);
    case CITE_CODE:
return InsetCitation::findInfo(cmdName); case FLOAT_LIST_CODE:
        return InsetFloatList::findInfo(cmdName);
    case HFILL_CODE:
        return InsetHFill::findInfo(cmdName);


What you're really implementing here is the Factory Pattern. One way to implement a factory, as you're doing here, is using a giant switch. Another way to do it is to register the content of the case statement in some map.

Something like (I probably get the function pointer syntax wrong):

class InsetCommandParams {
    typedef CommandInfo const * (FindInfoFn *)(std::string);
    static std::map<InsetCode, FindInfoFn *) findInfoFactory;
public:
    static void RegisterFindInfo(InsetCode code, FindInfoFn * func)
    {
        findInfoFactory[code] = func;
    }
};


class InsetBibitem {
    static bool firstTime = true;
public:
    InsetBibitem()
    {
       if (firstTime)
       {
           firstTime = false;
InsetCommandParams.RegisterFindInfo(BIBITEM_CODE, InsetBibitem::findInfo);
       }
    }
};

Then your InsetCommandParams::findInfo just calls into the map:

CommandInfo const * InsetCommandParams::findInfo(
    InsetCode code, std::string const & cmdName)
{
    return findInfoFactory[code](cmdName);
}

Thanks very much. This really helps me understand this "registration" thing. Possibly I'll try to implement this at some point, or just put a FIXME suggesting someone else do it....
This is one place where c#'s reflection tool is a real win.

Don't know C#, but it's at points like this that I miss Perl:
sub findInfo {
$insetCode = shift;
$InsetType = getInsetName($insetCode);
no strict refs;
return $InsetType::findInfo();
}

Couldn't possibly be simpler. And in languages like Ruby, and I think also Python, you can do even better, since types are objects.

rh

--
==================================================================
Richard G Heck, Jr
Professor of Philosophy
Brown University
http://frege.brown.edu/heck/
==================================================================
Get my public key from http://sks.keyserver.penguin.de
Hash: 0x1DE91F1E66FFBDEC
Learn how to sign your email using Thunderbird and GnuPG at:
http://dudu.dyn.2-h.org/nist/gpg-enigmail-howto

Reply via email to