vendredi 29 mai 2015

Removing ifs based on type and list of parameters

I will to refactor following recursive method:

public static void Initialize(Control control, DocumentContainer container, ErrorProvider provider)
        {
            if (control == null)
            {
                return;
            }

            var controlWithTextBase = control as IControlWithText;
            if (controlWithTextBase != null)
            {
               controlWithTextBase.DocumentLoaded = true;
               controlWithTextBase.Initialize(container, provider);
            }

            var custom = control as CustomCheckbox;
            if (custom != null)
            {
                custom.DocumentLoaded = true;
                custom.Initialize(container);
            }

            foreach (Control subControl in control.Controls)
            {
                Initialize(subControl, container, provider);
            }
        }

As you can see, depends on type of winforms control this code initialize a control. It starts with main form, and this contains custom controls(IControlWithText,CustomCheckbox) and default winforms forms. I would create 3 Initializators and to every a method CanInitialize depending on type of a control, but even then I have no idea how can I skip those "ifs", which I need to know if I need send this ErrorProvider to method Initialize.

I would be very grateful for your help!

Aucun commentaire:

Enregistrer un commentaire