我使用下面的条件语句来确保给出的城市名称的有效长度。城市长度应大于或等于3 且小于或等于20.
if(city.length()<3 || city.length()>20) return false;
else return true;
我被告知这个条件陈述可以进一步简化。是对的吗?那简化的代码是什么?
答案 0 :(得分:2)
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
SimpleModule testModule = new SimpleModule("MyModule")
.addDeserializer(Category.class, new IdWrapperDeserializer(Category.class))
mapper.registerModule(testModule);
return mapper;
}
或
public class ReflectionUtils {
//
public static boolean set(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
}
答案 1 :(得分:2)
我简化了IntelliJ IDEA IDE中的代码。
实际上它本身建议在我使用你的代码时简化。我建议你试试IntelliJ IDEA。
return city.length() >= 3 && city.length() <= 20;
如果您已经在使用IDE,只需将光标移动到带有警告的代码,然后按ALT + Enter并简化它。
答案 2 :(得分:2)
如果city.length()
便宜,请写
return city.length() >= 3 && city.length() <= 20
否则你应该预先计算city.length()
以避免两次评估的可能性:
const auto&& /*assuming C++, for Java, you need to use the specific type*/ l = city.length();
return l >= 3 && l <= 20;