开发者

Is there an elegant way to handle the rendered check much similar to an if else block

开发者 https://www.devze.com 2023-01-11 01:37 出处:网络
In the following scenario, the \"hasA\" condition is checked twice, is there a way to mimic this much similar 开发者_JAVA技巧to a if/else block so that the condition is evaluated only once

In the following scenario, the "hasA" condition is checked twice, is there a way to mimic this much similar 开发者_JAVA技巧to a if/else block so that the condition is evaluated only once

            <s:decorate template="/layout/display.xhtml">
                <h:outputText value="Print A." rendered="#{hasA}"/>
                <h:outputText value="Print B." rendered="#{!hasA}"/>
            </s:decorate>


You can write the condition in value attribute with EL expression

 <h:outputText value="#{hasA ? 'Print A.' : 'Print B.'}" />


To circumvent the problem, you can make sure the getter does not do any complicated stuff twice or basically returns a boolean. You should also make sure the getter is indempotent: calling it twice should yield the same result. To do so, you can either

  1. Compute lazily the boolean value and store it in a temporary field so that the second time the pre-computed value is returned.
  2. Change the logic so that the action that would result in a change of the boolean does actually update the boolean field, and the getter/setter is really just a getter/setter and does not compute anything.

The explanation is not crystal clear, but you should see the idea. I don't see anything wrong with having a simple getter evaluated multiple time.

0

精彩评论

暂无评论...
验证码 换一张
取 消