Extends and Implements

Verze:

18. 06. 2025

Zodpovědná osoba:

Dominik Šlechta

extends and implements Keywords on the Same Line as the Class Name

  • Rule: The extends and implements keywords MUST be declared on the same line as the class name.

  • Reason: This ensures the class declaration is clean and compact, making it easier to identify the class and its relationships with parent classes or interfaces. It also improves readability by preventing unnecessary line breaks.

Example (Correct):

class ClassName extends ParentClass implements ArrayAccess, Countable, Serializable {
    // Class body
}

Example (Incorrect):

class ClassName
    extends ParentClass
    implements ArrayAccess, Countable, Serializable {
    // Class body
}

Opening and Closing Braces for the Class

  • Rule (Opening Brace): The opening brace ({) for the class MUST go on its own line, immediately after the class declaration.

  • Rule (Closing Brace): The closing brace (}) for the class MUST go on the next line after the body of the class.

  • Reason: This helps maintain consistency in formatting and ensures that the class body is clearly delimited, making the code more readable and structured.

Example (Correct):

class ClassName extends ParentClass implements ArrayAccess, Countable, Serializable
{
    // Class body
} // Closing brace on its own line

Example (Incorrect):

class ClassName extends ParentClass implements ArrayAccess, Countable, Serializable {
    // Class body
} // Closing brace should not be on the same line as the body

Multi-line implements and extends Lists

  • Rule: If the list of implements or extends is split across multiple lines, each subsequent line MUST be indented once.

  • Rule: The first item in the list MUST be placed on the next line after extends or implements.

  • Rule: There MUST be only one interface per line in the case of implements (or extends when dealing with multiple parent classes).

  • Reason: Splitting long lists of interfaces or parent classes across multiple lines helps maintain readability, and indentation ensures that the code structure is clear.

Example (Correct):

class ClassName extends ParentClass implements
    ArrayAccess,
    Countable,
    Serializable
{
    // Class body
}

Example (Incorrect):

class ClassName extends ParentClass implements ArrayAccess, Countable, Serializable {
    // Class body
}

Summary:

  • extends and implements should be on the same line as the class name.

  • Opening and closing braces: The opening brace must be on its own line, and the closing brace should be after the body.

  • When splitting lists of interfaces or parent classes, each item should be on its own line and properly indented.