mardi 9 juin 2015

variable global const "macros" in C++ and optimal design patterns

I inherited some 10 year old code I have to complete. The code is in MFC (C++).

There's a .h file where the custom data structures are written and some const variables are in there as Globals. Some of these are used for MS Office file extensions, of type CString, and are declared as _T(".doc"), _T(".xls"), etc.

Obviously these are dated and need to be updated to recognize the Office 2007 and later extensions. My first brilliant idea was to use const_cast to change the constant if needed, but found out later that's a no-no and resulted in undefined behavior (sometimes it would switch back to .doc).

I then decided to create a struct and have two structs inherit from it. I created a void method in the base struct to make it abstract but otherwise it does nothing. Here's the code:

struct eOfficeExtensions{

    const CString WORD_EXTENSION;
    const CString EXCEL_EXTENSION;
    const CString WORDPAD_EXTENSION;
    const INT EXTENSION2007;

    eOfficeExtensions(CString word, CString excel, CString wordpad, INT ver) : 
        WORD_EXTENSION(word), EXCEL_EXTENSION(excel), WORDPAD_EXTENSION(wordpad), EXTENSION2007(ver){}

    //method to ensure base class is abstract
    virtual void Interface() = 0;
};

struct eOfficeExtensions2003 : public eOfficeExtensions{

public:


    eOfficeExtensions2003() : eOfficeExtensions(_T(".doc"), _T(".xls"), _T(".rtf"), 0){}

private:
    virtual void Interface(){}
};

struct eOfficeExtensions2007OrLater : public eOfficeExtensions{


    eOfficeExtensions2007OrLater() : eOfficeExtensions(_T(".docx"), _T(".xlsx"), _T(".rtf"), 1){}

private:
    virtual void Interface(){}
};

This feels like a ridiculous amount of code for what should be a simple conditional definition. What would an experienced programmer do?

Aucun commentaire:

Enregistrer un commentaire