Require using a colon after case instruction in switch statements

Created on 13 September 2018, over 6 years ago
Updated 13 November 2024, 5 months ago

In the coding standard, it is not explained whether a semicolon can be used after the "case" instruction. Technically, it is possible to use both a colon and a semicolon (case 1: or case 1;).

Look at the code below from the "field" module. Technically everything is correct.

// Extract the actual value against which the condition is checked.
switch ($key) {
  case 'field_name':
    $checked_value = $field_storage->getName();
    break;

  case 'field_id':
  case 'field_storage_uuid':
    $checked_value = $field_storage->uuid();
    break;

  case 'uuid';
    $checked_value = $field->uuid();
    break;

  case 'deleted';
    $checked_value = $field->isDeleted();
    break;

  default:
    $checked_value = $field->get($key);
    break;
}

However, many programmers who see something like this will wonder if this form is correct.

Coding standards: use colons in case statements →

For standardization proposes, I would suggest using one format in Coding standards → :

Always use a colon after the case instruction (e.g., case 1:), although technically you can also use a semicolon.

After this paragraph:

Always use curly braces even in situations where they are technically optional. Having them increases readability and decreases the likelihood of logic errors being introduced when new lines are added. The opening curly should be on the same line as the opening statement, preceded by one space. The closing curly should be on a line by itself and indented to the same level as the opening statement.

✨ Feature request
Status

Active

Component

Coding Standards

Created by

🇵🇱Poland Krzysztof Domański Poland

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024