سؤال

I have a composite component that calls my backing bean. Here I pass the parameters of some image:

<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" />

Here is the method

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();
}

And here is the appendAttribute method

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);
}

Do you have any idea regarding refactoring these unnested if statements? Because, as for me, it smells

هل كانت مفيدة؟

المحلول

Well, you could move the if statement into the appendAttribute method. You would then only have the conditional in one place.

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();
}

and:

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);
  }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top