在Java中,Collections类包含以下方法:
public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> c)
Run Code Online (Sandbox Code Playgroud)
它的签名因其对泛型的高级使用而闻名,因此在Java的Nutshell书籍和官方的Sun Generics Tutorial中都提到了它.
但是,我无法找到以下问题的令人信服的答案:
为什么类型的形式参数Collection<? extends T>,而不是Collection<T>?还有什么好处?
我和我的一位同事讨论了以下最佳实践问题.
大多数函数/方法都以一些参数检查开始.
我主张以下样式,避免嵌套.
if (parameter one is ugly) return ERROR;
if (parameter two is nonsense || it is raining) return ERROR;
// do the useful stuff
return result;
Run Code Online (Sandbox Code Playgroud)
来自更多功能/逻辑编程背景的他更喜欢以下内容,因为它减少了函数退出点的数量.
if (parameter one is ok) {
if (parameter two is ok && the sun is shining) {
// do the useful stuff
return result
}
}
return ERROR;
Run Code Online (Sandbox Code Playgroud)
你更喜欢哪一个?为什么?