Search code examples
coding-styleindentationcurly-braces

Where should we put the opening brace of a class in 1TBS style?


I have read the Indentation style entry on Wikipedia, but it's not very clear.

For K&R style, it says:

each function has its opening brace at the next line on the same indentation level as its header

Multi-line blocks inside a function, however, have their opening braces at the same line as their respective control statements

For the 1TBS (OTBS) style, it says:

functions have their opening braces on the same line separated by a space

It didn't talk about classes at all, but the Java style did:

the opening brace is on the same line not only for the blocks inside a function, but also for class or method declarations

If I am following the 1TBS style, where would the opening brace be placed for a class definition?

I also did a lot of searching (I prefer obtaining an answer immediately, instead of asking a question and waiting a long time), but no result.


Solution

  • There is unlikely to be an objective answer to this, as both the K&R and 1TBS styles emerged in the context of the C programming language, where there were no class definitions.

    Since derivative languages of C that support classes (e.g., C++, Java, etc.) share most of the syntax, it is only natural that the brace-style conventions that emerged for C would be used in and adapted for these derived languages. But they would be precisely that—derivations and adaptations. This is why the Wikipedia article mentions "Java" as a "variant" of the K&R style.

    There is no right place or wrong place to put the opening brace for a class definition, even when following K&R or 1TBS styles, since classes aren't part of either of those two styles. Inevitably, you'll be following some variant of those original styles that includes a convention for class definitions, and, in a variant, any convention you choose is valid.

    Ultimately, it matters not. Write the code in the way you think is readable (if you're writing it from scratch) or in the way that conforms to the other existing code files in the project. Conventions are merely that: conventions. There's no objective answer, and it doesn't matter.