Rules for DAX Code Formatting

With the modern editors that have automatic code formatting features, each one has its own code formatting style. Usually there are a few “common rules” for code formatting depending on the language, but there was nothing for DAX and in this article you will see a set of rules for DAX code formatting that can be used as a starting point to define your personal style.

UPDATE: you can format your DAX code following the rules in this article at www.daxformatter.com

The goal of this set of rules is to improve readability of a DAX expression. In order to do that, an expression is oftentimes split in several rows and this does not match very well with the user interface of measure grid in PowerPivot and SSDT Tabular editor. At the moment of writing, DAX Editor already support this code formatting style (use the Visual Studio shortcuts CTRL+K, CTRL+D to format the entire DAX document and CTRL+K, CTRL+F to format the current selection) and I hope that DAX Studio will support it soon in a future release.

This article will be very short showing the code formatting rules by using an example and the set of rules. Based on the feedback, I will keep this content updated to reflect the code standard we want to use in future article and books.

This is an example of a formatted DAX expression:

CALCULATE (
    SUMX (
        Orders,
        Orders[Amount]
    ),
    FILTER (
        ALL ( Customers ),
        CALCULATE (
            COUNTROWS ( Sales ),
            ALL ( Calendar[Date] ) 
        ) > 42 + 8 – 25 * ( 3 - 1 ) 
            + 2 – 1 + 2 – 1 
            + CALCULATE ( 
                  2 + 2 – 2 
                  + 2 - 2 
              ) 
            – CALCULATE ( 4 )
    )
)

The following is the set of rules:

Based on the last rule, calculated columns and measures are defined as follows:

CalculatedColumn = 
CALCULATE ( … )
 
Measure := 
CALCULATE ( … )

I would like to get your feedback. Remember, the goal is code readability and I know that many people would prefer different code style in order to simplify the editing of the query, but this is not the goal of this set of rules. As soon as we will have customizable code formatter integrated in all DAX editors, everyone will be able to define its own style and I really look forward for that day. In the meantime, I hope this could be a good starting point.