简体   繁体   中英

Refactoring Overloaded simple Methods in Java

I am quite new to Java. I have tried searching for an answer but can't quite seem to find one that I can completely understand.

So, I am aware of what an overloaded method is -- but how would I go about refactoring it to make it look less smelly?

say I had an overloaded method that looked like this

public static int subtract(int a, int b) {return a-b}
public static int subtract(int a, int b, int c) {return a-b-c}
public static int subtract(int a, int b, int c, int d) {return a-b-c-d}

and so on.

What would be an example of one way to refactor this? Please be detailed as I really want to learn how it would work.

Thank you

The best seems to use varargs , it'll handle any amount of parameters (minimum 2)

public static int subtract(int a, int... others) {
    return a - Arrays.stream(others).sum();
}


subtract(1, 2)             // -1
subtract(1, 2, 3, 4, 5, 6) // -19

Since the patterns seems to be subtracting all subsequent inputs from each input, I might suggest that you refactor to a single method which accepts an array:

public static int subtract(int[] inputs) {
    if (Objects.isNull(inputs) || inputs.length == 0) {
        throw new IllegalArgumentException("null input, returning");
    }

    int result = inputs[0];
    for (int i=1; i < inputs.length; ++i) {
        result -= inputs[i];
    }

    return result;
}

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