TabularEditor / BestPracticeRules

An official collection of standard Rules for use with Tabular Editor's Best Practice Analyzer.
120 stars 53 forks source link

[Rule Request] Default value missing from DIVIDE DAX function #60

Open swolfe2 opened 3 months ago

swolfe2 commented 3 months ago

Although [alternateresult] is an optional parameter within the DIVIDE function, it should be considered a best practice to provide a standard value in case the calculation was to fail.

I have a C# script to identify these today, but it would be great to be able to flag these within the BPA rules for Tabular Editor along with the ability to have a "fix script" to just supply BLANK() as the default value. image

// Script to check if the DIVIDE function in measures has a default parameter set
string a = "";
foreach (var measure in Model.AllMeasures)
{
    var expression = measure.Expression;

    // Check if the measure's expression contains the DIVIDE function
    if (expression.Contains("DIVIDE"))
    {
        // Regex to match DIVIDE function with and without alternativeresult
        var divideRegex = new System.Text.RegularExpressions.Regex(@"DIVIDE\s*\(\s*[^,]+,\s*[^,]+(?:,\s*[^)]+)?\s*\)");
        var match = divideRegex.Match(expression);
        if (match.Success)
        {
            // Check if the DIVIDE function has three parameters
            var parameters = match.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            if (parameters.Length == 2)
            {
                // DIVIDE function without a default parameter
                a = a + measure.Name + ",";
            }
        }
    }
}

// Remove the trailing comma
if (a.EndsWith(","))
{
    a = a.Substring(0, a.Length - 1);
}

// Display the results
if (string.IsNullOrEmpty(a))
{
    Info("All DIVIDE functions have a default parameter.");
}
else
{
    Info("The following measures do not have a default parameter set for DIVIDE:\n" + a);
}

Default Value in DIVIDE DAX.zip