Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring the code

I am learning the gradle tooling api. There I need to write two methods. One will call all the tasks defined in build.gradle file (There are more than 10 tasks defined )And another where I can specify the task names.(like clean, build etc)

I have below two methods which differs only in one line of code. I need your suggestions about how can we refactor these method two avoid the code duplication.

First Method. Will execute all the tasks from build.gradle

public boolean buildProject() {
        ProjectConnection connection = connector.connect();
        BuildLauncher build = connection.newBuild();
        try {
            build.run();// by default it executes all tasks
        }finally {
            connection.close();
        }
        return true;
    }

Second Method will execute only specified tasks

public boolean buildSpecificTask(String ...tasks ) {
    ProjectConnection connection = connector.connect();
    BuildLauncher build = connection.newBuild();
    build.forTasks(tasks);

    try {
        build.run();
    }finally {
        connection.close();
    }
    return true;
}

there is only a line difference of build.forTasks(tasks);

like image 940
Shirishkumar Bari Avatar asked Dec 14 '25 05:12

Shirishkumar Bari


2 Answers

public boolean build(String ...tasks) {
    ProjectConnection connection = connector.connect();
    BuildLauncher build = connection.newBuild();
    if (tasks.length > 0) {
        build.forTasks(tasks);
    }

    try {
        build.run();
    }finally {
        connection.close();
    }
    return true;
}
like image 196
Adam Sznajder Avatar answered Dec 15 '25 20:12

Adam Sznajder


If build.forTasks() is designed to do nothing when passed an empty array, then you don't need two methods. The argument list in your second method says String... tasks which means zero or more String arguments. When the number of arguments is zero, then tasks is equal to the empty array.

If build.forTasks does something with an empty array, see if you can make it do nothing for that case; then you only need one buildProject method.

like image 45
Carl Manaster Avatar answered Dec 15 '25 18:12

Carl Manaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!