Condividi tramite


X++ Standards: if ... else and switch Statements

Applies To: Microsoft Dynamics AX 2012 R3, Microsoft Dynamics AX 2012 R2, Microsoft Dynamics AX 2012 Feature Pack, Microsoft Dynamics AX 2012

This topic describes X++ code style standards for the if...else statement and the switch statement.

if...else

If you have an if...else construction, then use positive logic:

Preferred:

if (true)

{

    ...

}

else

{

    ...

}

Avoid:

if (!false)

{

    ...

}

else

{

    ...

}

It is acceptable to use negative logic if throwing an error, and in cases where the use of positive logic would make the code difficult to understand.

There should be a space character between the if keyword and the open parenthesis.

Switch Statements

Always end a case with a break statement (or return/throw). If you intentionally want to make use of the fall-through mechanism supported in X++, replace the missing break statement with a comment line:

    // Fall through

This comment line makes it visually clear to the reader that the fall-through mechanism is utilized.

Use 3 levels of indentation:

switch (Expression)

{

    case: Constant:

        Statement;

        break;

    ...

}

Do not put parentheses around cases. Warning icon

There should not be a space between the case keyword and the colon character.

Use a switch Instead of Nested if ... else Statements

Use switch statements instead of nested if...else statements.

Recommended:

switch (myEnum)

{

    case ABC::A:

    ...

        break;

    case ABC::B:

    ...

        break;

    case ABC::C:

    ...

        break;

    default:

    ...

        break;

}

Avoid:

if (myEnum == ABC::A)

{

    ...

}

else

{

    if (myEnum == ABC::B)

    {

        ...

    }

    else

    {

        if (myEnum == ABC::C)

        {

            ...

        }

        else

        {

           ...

        }

    }

}

See also

if and if ... else Statements

Switch Statements

Comparison of if and switch Statements

Announcements: New book: "Inside Microsoft Dynamics AX 2012 R3" now available. Get your copy at the MS Press Store.