mercredi 29 mai 2019

Please help to optimize a lot of "if statements"

I want get rid of if statements. Maybe will be better to use a lot of classes. And use needed class that can handle needed action.

Or it will be fabric pattern. Or it ok to use 30+ similar if statements.

I've tryed to make a Dictionary with string and object class. But not worked. (or my skills not good enought)

        if (node[DATA_CONNECTION_ELEMENT] != null)
        {               
            return new DataConnectionPropertyDataBinding(form, node[DATA_CONNECTION_ELEMENT], inputableEntity);
        }
        else if (node[FORM_PARAMETER_ELEMENT] != null)
        {
            return new FormParameterDataBinding(form, node[FORM_PARAMETER_ELEMENT], inputableEntity);
        }

        // + 30 more ifs


        else if (node[CLIPBOARD_ELEMENT] != null)
        {
            return new ClipboardDataBinding(form, node[CLIPBOARD_ELEMENT], inputableEntity);
        }
        else
        {
            return new ConstantDataBinding(form, node);
        }

Want to look something like

        foreach (var item in allThatShareSomeInterface)
        {
            if (item.CanHandle(node.Atributes[0]))
            {
                return item.neededObject();
            }
        }

Aucun commentaire:

Enregistrer un commentaire