Code action DI008
(Improvement) Remove superfluous CALCULATE
Description
Do not explicitly call CALCULATE
or CALCULATETABLE
, when it is not necessary.
Example 1 - Measure reference with no filter context modifiers
In the below examples, [Total Sales]
is a measure reference.
Change:
CALCULATE([Total Sales])
To:
[Total Sales]
Example 2 - Measure reference in a row context
Change:
AVERAGEX(Product, CALCULATE([Total Sales]))
To:
AVERAGEX(Product, [Total Sales])
Example 3 - Constant values are not affected by filter context modifications
Change:
VAR _salesWithTax = [Total Sales] * 1.25
RETURN
CALCULATE(_salesWithTax, Product[Color] = "Red")
To:
VAR _salesWithTax = [Total Sales] * 1.25
RETURN
_salesWithTax
Why is Tabular Editor suggesting this?
The CALCULATE
function is used to modify the filter context of a calculation and force a context transition when needed. However, when the expression is not impacted by a context transition, and the filter context is not modified, the CALCULATE
function is superfluous and can be removed (Example 1). This can make the code easier to read and understand.
Moreover, if the CALCULATE
function is only used to enforce a context transition and not modify the filter context (i.e. no filter arguments), but the expression is a simple measure reference, then the CALCULATE
function can be removed (Example 2), since measure references perform implicit context transitions, when evaluated in a row context.
Lastly, if the expression is constant (such as when referencing a variable that was defined outside of the CALCULATE
function, such as in Example 3 above), the modified filter context will not affect the result of the expression, and the CALCULATE
function including all filter arguments can be removed.