我创建了一个基于Bean属性动态构建rest URI的方法,最初是命令式的,然后我将其重构为函数式风格,这是我第一次进行函数式编程。 命令式和函数式都按预期工作,但我对函数式可读性不满意,函数式接缝对这种方法来说是一种过度杀戮,或者可能是因为我仍然是一个新手函数式程序员!
您将如何将此方法重构为更简洁的功能方式?
或者你会保持它势在必行吗?
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.lang.reflect.Method;
import org.springframework.beans.BeanUtils;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.util.UriComponentsBuilder;
public String functionalBuildRestUri() throws Exception {
final UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance().scheme("https")
.host("foo.com").path("/offers");
//here is the functional
List<PropertyDescriptor> propDescList = Arrays.asList(BeanUtils.getPropertyDescriptors(getClass()));
//this part is readable and precis, but to enable it had to add 4 methods
propDescList.stream().filter(notClassProp())
.filter(notNullPropValue())
.collect(Collectors.toMap(PropertyDescriptor::getName, propValue()))//conversion to map doesn't feel good to me how can I avoid it?
.forEach(buildRestParam(uriBuilder));
return uriBuilder.build().toUriString();
}
public String imperativeBuildRestUri() throws Exception {
final UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance().scheme("https")
.host("foo.com").path("/offers");
PropertyDescriptor[] propDescArray = BeanUtils.getPropertyDescriptors(getClass());
for (PropertyDescriptor propDesc : propDescArray) {
String propName = propDesc.getName();
if (!propName.equals("class")) {
Method getPropMethod = propDesc.getReadMethod();
Object propValue = getPropMethod.invoke(this);
if (propValue != null) {
if(propValue instanceof Date){
String dateStr = new SimpleDateFormat(DATE_FORMAT).format((Date)propValue);
uriBuilder.queryParam(propName, ":"+dateStr);
}else{
uriBuilder.queryParam(propName, propValue);
}
}
}
}
return uriBuilder.build().toUriString();
}
所有这些方法都是在功能重构后添加的
// I couldn't avoid being imperative here, how can we refactor it to more functional style
private BiConsumer<String, Object> buildRestParam(final UriComponentsBuilder uriBuilder) {
return (propName, propValue) -> {
if (propValue instanceof Date) {
String dateStr = new SimpleDateFormat(DATE_FORMAT).format((Date) propValue);
uriBuilder.queryParam(propName, ":" + dateStr);
} else {
uriBuilder.queryParam(propName, propValue);
}
};
}
private Predicate<? super PropertyDescriptor> notNullPropValue() {
return propDesc -> {
return propValue().apply(propDesc) != null;
};
}
private Predicate<? super PropertyDescriptor> notClassProp() {
return propDesc -> {
return !propDesc.getName().equals("class");
};
}
private Function<? super PropertyDescriptor, ? extends Object> propValue() {
return (propDesc) -> {
try {
return propDesc.getReadMethod().invoke(HotelOfferSearchCommand.this);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
};
}
新代码的大部分冗长与函数式编程无关。您重构了代码,将每个 lambda 表达式放入其自己的方法中,这当然破坏了 lambda 表达式的主要优点之一:紧凑性。即使代码足够复杂以证明创建方法的合理性,该方法也应该执行实际工作,然后,您可以在需要函数的地方使用方法引用。
这些方法还受到不必要(甚至不鼓励,因为在返回类型中)使用通配符的影响。您还使用了详细语法
parameter -> { return expression; }
,其中 parameter -> expression
是可能的。
还存在其他问题,例如不必要地为每个异常类型创建不同的
catch
子句,当所有异常类型都执行相同操作或在创建 List
之前将数组包装到 Stream
中,而不是直接流式传输数组或使用代码时重复,最后一点适用于命令式变体和函数式变体。
你可以写:
public String functionalBuildRestUri() throws Exception {
final UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance()
.scheme("https").host("foo.com").path("/offers");
Function<PropertyDescriptor, Object> propValue = propDesc -> {
try { return propDesc.getReadMethod().invoke(HotelOfferSearchCommand.this); }
catch(ReflectiveOperationException e) { throw new RuntimeException(e); }
};
Arrays.stream(BeanUtils.getPropertyDescriptors(getClass()))
.filter(propDesc -> !propDesc.getName().equals("class"))
.filter(propDesc -> propValue.apply(propDesc) != null)
.forEach(propDesc -> {
Object value = propValue.apply(propDesc);
if (value instanceof Date)
value = ":"+new SimpleDateFormat(DATE_FORMAT).format(value);
uriBuilder.queryParam(propDesc.getName(), value);
});
return uriBuilder.build().toUriString();
}
无需任何额外方法。
这可能不是最好的选择,因为确实存在一个缺陷,即缺少元组或对类型来保存要通过流传递的两个值。通过使用
Map.Entry
作为替代,但不填充 Map
,我们可以将操作表示为
public String functionalBuildRestUri() throws Exception {
final UriComponentsBuilder uriBuilder = UriComponentsBuilder.newInstance()
.scheme("https").host("foo.com").path("/offers");
Function<PropertyDescriptor, Object> propValue = propDesc -> {
try { return propDesc.getReadMethod().invoke(HotelOfferSearchCommand.this); }
catch(ReflectiveOperationException e) { throw new RuntimeException(e); }
};
Arrays.stream(BeanUtils.getPropertyDescriptors(getClass()))
.filter(propDesc -> !propDesc.getName().equals("class"))
.map(propDesc -> new AbstractMap.SimpleImmutableEntry<>(
propDesc.getName(), propValue.apply(propDesc)))
.filter(entry -> entry.getValue() != null)
.forEach(entry -> {
Object value = entry.getValue();
if (value instanceof Date)
value = ":"+new SimpleDateFormat(DATE_FORMAT).format(value);
uriBuilder.queryParam(entry.getKey(), value);
});
return uriBuilder.build().toUriString();
}
或者
Arrays.stream(BeanUtils.getPropertyDescriptors(getClass()))
.filter(propDesc -> !propDesc.getName().equals("class"))
.map(propDesc -> new AbstractMap.SimpleImmutableEntry<>(
propDesc.getName(), propValue.apply(propDesc)))
.filter(entry -> entry.getValue() != null)
.map(e -> e.getValue() instanceof Date?
new AbstractMap.SimpleImmutableEntry<>(e.getKey(),
":"+new SimpleDateFormat(DATE_FORMAT).format(e.getValue())):
e)
.forEach(entry -> uriBuilder.queryParam(entry.getKey(), entry.getValue()));
使用这两个变体,
propValue
函数每个元素仅计算一次,而不是像第一个变体和原始代码中那样计算两次,其中检查null
属性值和终端操作都对其进行评估。
请注意,仍有改进的空间,例如当您首先可以使冒号成为格式模式字符串的一部分时,没有理由在
":"
操作之后添加 format
。
这是否是对循环的改进,是你必须自己决定的事情。并非所有代码都必须重写为函数式风格。至少,如上面的示例所示,它不必比命令式代码更大......