重构未经证实的条件语句

时间:2013-07-05 12:22:34

标签: java refactoring conditional statements

我有一个调用我的支持bean的复合组件。在这里我传递一些图像的参数:

<h:outputText value="#{MyBBean.formRequest(
   cc.attrs.type, 
   cc.attrs.orientation, 
   cc.attrs.title, 
   cc.attrs.width, 
   cc.attrs.height, 
   cc.attrs.xlabel, 
   cc.attrs.ylabel, 
   cc.attrs.value)}" 
escape="false" />

这是方法

public boolean formRequest(
      final String type,
      final String orientation,
      final String title,
      final String width,
      final String height,
      final String xlabel,
      final String ylabel) {

   // some actions here

   if (height != null) {
      appendAttribute(HEIGHT_ATTRIBUTE_NAME, height, request);
   }

   if (width != null) {
      appendAttribute(WIDTH_ATTRIBUTE_NAME, width, request);
   }

   // the like

   if (ylabel != null ) {
      appendAttribute(Y_LABEL_ATTRIBUTE_NAME, ylabel, request);
   }

   // other actions

   return request.toString();
}

这是appendAttribute方法

private void appendAttribute(final String attributeName, 
      final String attributeValue, final StringBuilder builder) {

   builder.append(attributeName);
   builder.append(EQUALS_CHAR);
   builder.append(attributeValue);
   builder.append(AMPERSAND_CHAR);
}

您是否有任何关于重构这些unnested if语句的想法?因为,对我来说,它闻起来味道

1 个答案:

答案 0 :(得分:1)

好吧,您可以将if语句移动到 appendAttribute 方法中。然后,您只能在一个地方拥有条件。

public boolean formRequest(
  final String type,
  final String orientation,
  final String title,
  final String width,
  final String height,
  final String xlabel,
  final String ylabel) {

  appendAttribute(HEIGHT_ATTRIBUTE_NAME, height, request);
  appendAttribute(WIDTH_ATTRIBUTE_NAME, width, request);
  appendAttribute(Y_LABEL_ATTRIBUTE_NAME, ylabel, request);
  return request.toString();
}

private void appendAttribute(final String attributeName, 
  final String attributeValue, final StringBuilder builder) {

  if(attributeValue != null) {
      builder.append(attributeName);
      builder.append(EQUALS_CHAR);
      builder.append(attributeValue);
      builder.append(AMPERSAND_CHAR);
  }
}