jeudi 15 décembre 2022

Best practice to avoid function's parameter manipulation

I have the following abstract code snippet:

// definitions
    MyClass1 mc1 = new MyClass1();
    MyClass2 mc2 = new MyClass2();
    List<String> elements = new ArrayList<>();

// some black magic...

// setters
    mc2.setElements(elements);
    String id = saveMyClass2(mc2)
    mc1.setMc1Id(id);

// Some other black magic on mc1 

I'm using the setters flow in multiple parts of my code. I wanted to elaborate this by a wrapper function like this:

void doSettings(MyClass1 mc1, MyClass2 mc2, List<String> elements) {
        mc2.setElements(elements);
        String id = saveMyClass2(mc2)
        mc1.setMc1Id(id);
}

But I am doing a parameter manipulation in this function which I want to avoid. Also cloning the classes is not an option, they are 3 layers deep and it takes too much effort to create deep copy.

So do you know any best practice or coding pattern which helps to avoid code duplication?

Aucun commentaire:

Enregistrer un commentaire