Shirish Bari
Shirish Bari

Reputation: 2722

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);

Upvotes: 3

Views: 84

Answers (2)

Carl Manaster
Carl Manaster

Reputation: 40336

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.

Upvotes: 3

Adam Sznajder
Adam Sznajder

Reputation: 9206

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;
}

Upvotes: 4

Related Questions