kotlin-style-guide
kotlin-style-guide copied to clipboard
Class layout
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.
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?
Are those constants really the most important thing you want the reader of your class to see?
Valid question. I guess not.
What's the advice on public first vs private first?
@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 what about properties with state? I try to place private properties first, then public ones
Reference: https://google.github.io/styleguide/javaguide.html#s3.4.2-class-member-ordering
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.
Are properties with custom getters or setters sorted with property declarations or with method declarations?