简体   繁体   中英

What is the best approach to encapsulate multiple method calls?

Is there some principle to follow in multiple method calls on Java?

I know about Facade, but in single methods, not service methods, sometimes we need to call other single methods that have a single responsibility, but doing this, I will break this in this method then make multiple calls. For example:

private void doSomethingA(){

} 

private void doSomethingB(){

}   

private void doSomethingC(){

}  

//Am I breaking some rules here? What is the best approach?
private void processSomething(){
   doSomethingA();
   doSomethingB();
   doSomethingC();
}

What you're doing is perfectly acceptable, although your syntax is incorrect. Splitting large methods into smaller, more singly purposed, more readable, more testable methods and calling them from another method is good practice.

If there are a large number of processes or you use the same sequence often you could implement the processing as a sequence using an enum .

public enum Engine {

    A {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            },
    B {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            },
    C {

                @Override
                void doIt(Object to) {
                    // Do what you need to do.
                }
            };

    abstract void doIt(Object to);

    public void go(Object to) {
        for (Engine e : Engine.values()) {
            e.doIt(to);
        }
    }
}

This can be enhanced in many ways (which is why I like it). You can encode alternative orders of execution in an Iterable . You can add, remove and reorder the processes in just one place. The names of the enum can be greatly simplified. And many more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM