views:

79

answers:

2

I have a Win32 C++ program that validates user input and updates the UI with status information and options. Currently it is written like this:

void ShowError() {
    SetIcon(kError);
    SetMessageString("There was an error");
    HideButton(kButton1);
    HideButton(kButton2);
    ShowButton(kButton3);
}

void ShowSuccess() {
    SetIcon(kError);

    std::String statusText (GetStatusText());
    SetMessageString(statusText);

    HideButton(kButton1);
    HideButton(kButton2);
    ShowButton(kButton3);
}

// plus several more methods to update the UI using similar mechanisms

I do not likes this because it duplicates code and causes me to update several methods if something changes in the UI.

I am wondering if there is a design pattern or best practice to remove the duplication and make the functionality easier to understand and update.

I could consolidate the code inside a config function and pass in flags to enable/disable UI items, but I am not convinced this is the best approach.

Any suggestions and ideas?

+1  A: 

If you can encapsulate all the states into some logical values to occupy an enum of sorts you can give the Window a stateChanged signal, which represents any change to some "global" state of the window. I like to separate the display logic of all my widgets into different functions, like so:

kButton1_onStateChanged(WindowState state)
{
    kButton1.setVisible(state == WS_FAILURE);
}

kButton2_onStateChanged(WindowState state)
{
    kButton1.setVisible(state == WS_FAILURE);
}

kButton3_onStateChanged(WindowState state)
{
    kButton1.setVisible(state == WS_SUCCESS);
}

If you use Qt, you can get signals and slots to do this for you. If your rules are simple enough, you can put all this logic into the UI file, which lets designers handle all that UI stuff and not touch your code.

Travis Gockel
+1  A: 

I would recommend Observer Pattern and State Pattern, when an validation happens to be successful or unsuccessful, attached buttons can change their state according to information provided in "notify" method. Please refer to GoF's book for further details, or just google them. Hope it helps.

baris_a
Yours and Travis's replies match the direction I was heading in. Thanx for the feedback guys!
TERACytE