kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

Class layout

Open yole opened this issue 9 years ago • 9 comments

Generally, the contents of a class is sorted in the following order:

  • Property declarations
  • Initializer blocks
  • Method declarations
  • Companion object

Do not sort the method declarations alphabetically or by visibility, and do not separate regular methods from extension methods. Instead, put related stuff together, so that someone reading the class from top to bottom would be able to follow the logic of what's happening. Choose an order (either higher-level stuff first, or vice versa) and stick to it.

yole avatar May 31 '16 17:05 yole

I would like to discuss the positioning of the companion object. In many cases it contains constants and constants are usually placed at the top of a class in Java. What was the motivation for using this style?

cypressious avatar Jun 01 '16 14:06 cypressious

Are those constants really the most important thing you want the reader of your class to see?

yole avatar Jun 01 '16 14:06 yole

Valid question. I guess not.

cypressious avatar Jun 01 '16 14:06 cypressious

What's the advice on public first vs private first?

voddan avatar Jun 08 '16 07:06 voddan

@voddan Neither. Put related stuff together. If private methods are related to the implementation of a public method, put them next to that method.

yole avatar Jun 08 '16 07:06 yole

@yole what about properties with state? I try to place private properties first, then public ones

voddan avatar Jun 08 '16 07:06 voddan

Reference: https://google.github.io/styleguide/javaguide.html#s3.4.2-class-member-ordering

yole avatar Aug 25 '16 14:08 yole

In some cases companion object holds the factory methods to create the class. I think this is really important for the reader of a class to see first. Do think the companion in this case still need to be placed underneath in this case?

Regarding constants in many cases they are some kind of specification for the class so I think it's good to have them at the top.

So I personally prefer to have companion at the very top of the class.

Jeevuz avatar Oct 17 '17 09:10 Jeevuz

Are properties with custom getters or setters sorted with property declarations or with method declarations?

mike-burns avatar May 30 '19 19:05 mike-burns