如何在方法中使用带有“后备”参数的接口?

时间:2019-09-02 21:30:03

标签: java design-patterns java-8 interface api-design

我正在用Java语言编写一些代码,并且由于我从未接受过任何真正的教育,因此很难确定这是否可以。我想在类中强制使用save(ConfigurationSection),但如果不可用,则允许使用save(String)。我意识到我可以在调用此方法之前进行此转换。那是我应该做的吗?

def bit_reverse_sort(array, bits):
    """Returns the list array sorted by reverse bit index

    Arguments:
    array -- list to be sorted
    bits -- the number of bits that each number is represented by
    """
    sorted_array = list(range(len(array)))
    for index, frame in enumerate(array):
        # converts index into byte form
        index_byte = '{:0{width}b}'.format(index, width=bits)

        # reverses byte and converts to int for index
        sorted_array[int(index_byte[::-1], 2)] = frame

    return sorted_array

def fft(x, N):
    """Yields the complex result of the fft of x

    Arguments:
    x -- list of frames
    N -- length of x

    Only works for radix 2 case
    """
    if N == 1:
        return x
    else:
        even_x = fft(x[::2], N // 2)
        odd_x = fft(x[1::2], N // 2)

        combined_x = even_x + odd_x
        for i in range(N // 2):
            t = combined_x[i]
            combined_x[i] = t + exp(-2 * pi * 1j * (i / N))
            combined_x[i + (N // 2)] = t - exp(-2 * pi * 1j * (i / N))

        return combined_x

def get_biggest_frequency(array):
    array = [abs(x) for x in array[1:len(array) // 2]]
    return(array.index(max(array)))

for i in get_samples(input("Input file: ")):
    print(get_biggest_frequency(fft(bit_reverse_sort(list(i), 12), len(i))))
    break

我想知道是否可以这样做。也是任何对术语没有任何真正知识的人都可以相对理解的优质资源。

2 个答案:

答案 0 :(得分:2)

  

我想在课堂上强迫使用save(ConfigurationSection)

很难强迫用户在另一种方法上使用一种重载方法。如果我有两个选择,则选择最简单的一个,然后让API为我完成所有肮脏的工作。如果有一个诱人的ConfigurationSection选项,我将不会自己构造String,除非前者为我提供了一种更灵活/更细粒度/更高效的方式。

不过,您可能会很好地记录这些方法。清楚说明哪种方法更可取,为什么。

  

如果不可用,则允许使用save(String)

我不明白。有一种方法或两种方法。如果用户无法构建ConfigurationSection,并不意味着save(ConfigurationSection)神奇地消失了,而save(String)出现了。您的界面仍然是这两种方法。

  

我想知道是否可以这样做。

是的,你是。您的代码对我来说绝对不错。

Claims.getDataManager().getData().createSection(path)

是可以将String转换为ConfigurationSection的默认方法,只要它不会带来任何副作用并且对调用方透明即可。就像用户熟悉(或可以熟悉)的快捷方式。

顺便说一句,我喜欢你的问题。它看起来简单而谦虚。

答案 1 :(得分:1)

与其提供这种default方法,不如在您的fromString类内创建一个ConfigurationSection适配器方法

public static ConfigurationSection fromString(String s) {
    // ...
}

或者更好,如果您有一些其他逻辑可用于创建构建器类

public class ConfigurationSectionBuilder {
    // dependencies and constructors
    private DataManagerData dataManagerData;

    public ConfigurationSection fromString(String s) {
        return dataManagerData.createSection(s);
    }
}

接口应该就这么简单。您想添加什么新的创建ConfigurationSection的方式(例如,从Long开始),并且为此需要一些其他服务依赖项?是 SRP

的明显紫罗兰色

也不要这样创建“链”

Claims.getDataManager().getData().createSection(path)

这是得墨meter耳法则

的紫罗兰色