【发布时间】:2018-02-20 05:54:28
【问题描述】:
我有以下代码。如您所见,我正在执行类似的逻辑,但一次用于自行车,一次用于汽车。我可以使用<K> 来减少重复的代码吗?我没有使用过<K>,所以我不确定我可以在哪里以及如何准确地合并它。我在哪里可以决定是拨打getCarsWithFeature还是getBikesWithFeature?
最好的做法是减少行数(可能会降低可读性)还是拥有类似重复的代码?
public Set<Car> getPremiumCars(String filter) {
final Callable<Set<Car>> retryGetCars = new RetryingCallable<>(retryStrategy(), getCars(filter));
return retryGetCars.call();
}
public Callable<Set<Car>> getCars(String feature) {
return new Callable<Set<Car>>() {
@Override
public Set<Car> call() throws Exception {
Set<Car> cars = getCarsWithFeature(feature);
return Collections.unmodifiableSet(cars);
}
};
}
public Set<Bike> getPremiumBikes(String filter) {
final Callable<Set<Bike>> retryGetBikes = new RetryingCallable<>(retryStrategy(), getBikes(filter));
return retryGetBikes.call();
}
public Callable<Set<Bike>> getBikes(String feature) {
return new Callable<Set<Bike>>() {
@Override
public Set<Bike> call() throws Exception {
Set<Bike> bikes = getBikesWithFeature(feature);
return Collections.unmodifiableSet(bikes);
}
};
}
【问题讨论】:
-
是的,如果您有 Car 和 Bike 的通用(基类)类型,则可以
-
您可能可以,但 Cars 和 Bikes 完全不同,我认为您会遇到泛型问题。将所有通用代码分解到一个抽象基类中可能会更好,因为这仍然允许您专门化 Bike 或 Car 子类所需的任何代码。
-
这个问题的答案应该与
getCarsWithFeature和getBikesWithFeature对应。是否使用泛型,它们似乎是必须进行的不同调用。 -
谢谢@Piro。是的,它们确实是不同的电话。在这种情况下不能使用泛型吗?
-
为什么代码中充斥着
Callables和其他无关的东西?既然你在基础方面遇到问题,你应该坚持使用基本代码,而不是无缘无故地让它看起来“高级”。
标签: java oop generics inheritance