如何避免深度if语句以避免pmd中的警告



这样我就可以减少下面代码的if then语句

if (presenterManager != null) {
        IFieldPresenter modeFieldPresenter = presenterManager.getFieldPresenter(ATTR_MODE);
        if (modeFieldPresenter != null) {
            String modeLV =  ((ListBoxValue)modeFieldPresenter.getState().getSingleValue()).getValue();
           String customerAccountPK = getContext().getRequestParam("parentPK");
           String customerAccountId = toObjectId(customerAccountPK);
            LOG.debug(" modeLV = "+modeLV);
            LOG.debug( "customerAccountId = "+customerAccountId);
            if(!LV_AUTOMATIC.equals(modeLV)) {
                Window.open(CONFIGURE_URL_PREFIX + customerAccountId, "_blank", "");
                return getInitialEvent();
            }
        }
    }

我想避免if(!LV_AUTOMATIC.equals(modeLV))这个if语句的深度if

在Java 8中可以这样做。

Optional<InitalEvent> event = Optional.ofNullable(presenterManager)
    .map(p -> p.getFieldPresenter(ATTR_MODE))
    .map(p -> (ListBoxValue)p.getState().getSingleValue()).getValue()) 
    .filter(!LV_AUTOMATIC.equals(modeLV))
    .map(modeLV -> {
       String customerAccountId = toObjectId(getContext().getRequestParam("parentPK"));
        LOG.debug(" modeLV = "+modeLV+", customerAccountId = "+customerAccountId);
        Window.open(CONFIGURE_URL_PREFIX + customerAccountId, "_blank", "");
        return getInitialEvent();
    });
}

最新更新