jeudi 25 février 2016

How can I avoid semi-repeating groups of methods in java?

Let's say I have written the following methods:

public void submitForm1() {
        open();
        setField(1, "blah");
        setField(3, "bla");
        setField(4, "blah blah");
        submit();
    }

public void submitForm2() {
        open();
        setField(1, "blah");
        checkBox(1 , true);
        submit();
}

....

public void submitForm100() {
        open();
        setField(1, "bla");
        setField(2, "bla bla");
        setField(3, "blah");
        setArea(1, "blah blah");
        submit();
}

These methods make me feel I'm constantly repeating myself. I feel like it should be written like this:

public void submitForm1() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {SET_FIELD, 3, "bla"},
            {SET_FIELD, 4, "blah blah"}
        );
    }

public void submitForm2() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "blah"},
            {CHECKBOX, 1, true}
        );
}

....

public void submitForm100() {
        MyMethods.submitForm(
            {SET_FIELD, 1, "bla"},
            {SET_FIELD, 2, "bla bla"},
            {SET_FIELD, 3, "blah"},
            {SET_AREA, 1, "blah blah"},
        );
}

This way I won't have to repeat all of those open and submit methods over and over again.

Is there a way to do this?





Aucun commentaire:

Enregistrer un commentaire