简体   繁体   中英

Having multiple methods doing the same thing

We're creating an SDK. I've had a discussion with a mate because he says it's better to have different methods that do the same with one slightly difference than having a method with flags that changes its behaviour. I'm going to show an example which is similar to the discussion we had.

If one of the methods of the SDK will sort a collection, the current implementation contains an enum with the possible sort algoritms.

public enum Algorithm {
    BUBBLESORT,
    QUICKSORT
}

and an interface

interface Sorting {
    Collection sort(Collection input, Algorithm alg);
}

My mate's approach is to have as many sort methods as kind of algorithms

interface Sorting {
    Collection quickSort(Collection input);
    Collection bubbleSort(Collection input);
}

He says having the algorithm as a parameter is weird. what do you think? for other scenarios than the sort one, is it better to have multiple methods for the same feature?

interface Sorting {
    Collection sort(Collection input);
}

class Quicksort : Sorting {
   Collection sort(Collection input) {
   }
}

class BubbleSort: Sorting {
    Collection sort(Collection input) {
    }
}

It depends on individuals approach and opinion. From your mate's point, having all your algorithms in a single method might not be good from maintenance perspective.

Lets consider your approach,

interface Sorting {
    Collection sort(Collection input, Algorithm alg);
}

To implement this. How would you go about it?

Class DefaultSorting implements Sorting {
     Collection sort(Collection input, Algorithm alg){
        //implement algo1
        //implement algo2
        //implement algo3
        //... In case more in the future
        // algo4, algo5?
     }
}

If you still want to choose other ways, You can also go for separate classes per function or Factory Methods which might be like,

interface Sorting {
    Collection sort(Collection input);
}

class QuickSort implements Sorting{
    Collection sort(Collection input){
      //Quick Sort
    }
}

class BubbleSort implements Sorting{
    Collection sort(Collection input){
      //Bubble Sort
    }
}

public enum Algorithm {
    BUBBLESORT,
    QUICKSORT
}

class AlgorithmFactory {
    public static Sorting getSorting(Algorithm alg){
       if(alg == Algorithm.BUBBLESORT)
           return new BubbleSort();
       if(alg == Algorithm.QUICKSORT)
           return new QuickSort();
    }
}

Usage:

Sorting bubbleSort = AlgorithmFactory.getSorting(Algorithm.BUBBLESORT);
Collection output = bubbleSort.sort(input);

If possible you can check on design principles and design patterns

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