期望排序列表是一个糟糕的设计吗?

时间:2017-11-13 05:57:50

标签: java algorithm

让我们说我希望用Java解决问题 - Find maximum product of 3 numbers in an array

由于它很容易解决问题所提供的输入List已经排序,所以如果我的API方法需要一个排序的输入,这会是一个糟糕的设计吗?

我假设我的API方法无法控制数据来源的场景。输入列表人口。我认为这是您编写API时的常用假设。

我还假设输入可能非常大(一百万件左右)。

对上游施加此类限制是否过于严格?

Related Question

编辑:我引用该问题作为示例。我想说,从一开始(插入元素时)保持数字列表更有意义吗?由于数据集合上的大多数问题通常在收集已经排序时很容易,或者从数据流一开始就排序的数字列表也存在某些缺点?

2 个答案:

答案 0 :(得分:4)

The JDK method Collections.binarySearch() specifies in its documentation:

The list must be sorted into ascending order according to the natural ordering of its elements (as by the sort(List) method) prior to making this call. If it is not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be found.

This of course requires that you've read and understood the prerequisites for this method. Problematic is also that in case the list isn't sorted, you don't get an error, but undefined behaviour (i.e. usually the wrong index returned). That certainly doesn't sound like good design.

However, what are the alternatives? You can't call sort() inside the method, that would be too expensive when the lists are already sorted, not to mention confusing when the side-effect of calling the method would be sorting the list.

So as you see, in some cases we need to make some prerequisites to avoid even worse design. If a programmer doesn't read the documentation, it's not really the API maker's fault. Of course you want to make your code intuitive and easy to use, but sometimes it's just not possible or realistic.

答案 1 :(得分:1)

我认为这是糟糕的设计。

为什么呢?

@Kayaman已经说过,一个提供未排序列表的调用者可能会得到错误的结果,并且没有暗示他做错了什么。

第二个原因:您将实现细节传播到API设计中。可能有其他实现不需要对列表进行排序(例如,三个数字的产品可以在未排序的列表中以O(n)完成)。

所以:

  • 提供处理未排序列表的方法。
  • 如果您的呼叫者可能已为您准备了已排序的列表版本,请添加第二个方法,其名称应明确说明是否需要排序列表。

或者,如果从上下文中确定列表始终是排序的,那么它不应该用作普通列表,而是封装在一个保证"排序"的类中。属性。