Home > Software engineering >  Dart abstract static method
Dart abstract static method

Time:10-12

I want to create an abstract Sort class for my class project using dart which I will extend with Sorting algorithm classes like MergeSort, QuickSort, Heap, etc. I wrote the below code but I cannot create an abstract static sort method which I can override and use like

Heap.sort(arr)
OR
MergeSort.sort(arr)

Do anyone know why I cannot create abstract static method and also if you have any other way of doing this please feel free to guide me :D

    abstract class Sort {
  // void sort(List array);
  static void sort(List array);

  bool isSorted(List array) {
    for (int i = 0; array.length > i - 1; i  ) {
      if (array[i] > array[i   1]) {
        return false;
      }
    }

    return true;
  }

  void swap(arr, i, j) {
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
  }
}

CodePudding user response:

As the answer linked above says, you can't have abstract static methods.

An abstract method does just one thing, it adds a method signature to the interface of the class, which other (non-abstract) classes implementing the interface then has to provide an implementation for. The abstract class doesn't add implementation.

Static methods are not part of the interface, so being abstract and static means it has no effect at all. It's a method with no implementation, which nobody can ever implement. So you're not allowed to do that.

To actually have separate classes representing different sorting algorithms, just do that directly using instance methods. That's the strategy object pattern.

abstract class Sorter<T> {
  void sort(List<T> values);
  int compare(T value1, T value2);
  void swap(List<T> values, int index1, int index2) {
    T tmp  = values[index1];
    values[index1] = values[index2];
    values[index2] = tmp;
  }
}
abstract class HeapSort<T> extends Sorter<T> {
  void sort(List<T> values) {
    // heap sort algorithm.
  }
}

abstract class MergeSort<T> extends Sorter<T> {
  void sort(List<T> values) {
    // merge sort algorithm.
  }
}

mixin ComparableSorter<T extends Comparable<T>> on Sorter<T> {
  int compare(T value1, T value2) => value1.compareTo(value2);
}

class ComparableHeapSort<T extends Comparable<T>> 
  extends HeapSort<T> with ComparableSorter<T> {}

class CustomCompareHeapSort<T> extends HeapSort<T> {
  int Function(T, T) _compare;
  CustomCompareHeapSort(int Function(T, T) compare) : _compare = compare;
  int compare(T value1, T value2) => _compare(value1, value2);
}

There are plenty of options about how to slice the API and abstract over different parts of it.

I recommend figuring out what use-cases you want to support, before starting the API design.

  • Related