在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):raywenderlich/kotlin-style-guide开源软件地址(OpenSource Url):https://github.com/raywenderlich/kotlin-style-guide开源编程语言(OpenSource Language):开源软件介绍(OpenSource Introduction):The Official raywenderlich.com Kotlin Style Guide (in progress)This style guide is different from others you may see, because the focus is centered on readability for print and the web. We created this style guide to keep the code in our tutorials consistent. Our overarching goals are conciseness, readability and simplicity. You should also check out our other style guides: InspirationThis style-guide is somewhat of a mash-up between the existing Kotlin language style guides, and a tutorial-readability focused Swift style-guide. The language guidance is drawn from:
Alterations to support additional readability in tutorials were inspired by the raywenderlich.com Swift style guide. Android Studio Coding StyleIt is possible to get Android Studio to adhere to these style guidelines, via a rather complex sequence of menus. To make it easier, we've provided a coding style that can be imported into Android Studio. The file can be found here. To install the file, open Android Studio Settings and go to Editor > Code Style > Kotlin, then click the gear menu and choose Import Scheme.... From now on, projects you create should follow the correct style guidelines. Table of Contents
NomenclatureOn the whole, naming should follow Java standards, as Kotlin is a JVM-compatible language. PackagesPackage names are similar to Java: all lower-case, multiple words concatenated together, without hypens or underscores: BAD: com.RayWenderlich.funky_widget GOOD: com.raywenderlich.funkywidget Classes & InterfacesWritten in UpperCamelCase. For example MethodsWritten in lowerCamelCase. For example FieldsGenerally, written in lowerCamelCase. Fields should not be named with Hungarian notation, as Hungarian notation is erroneously thought to be recommended by Google. Example field names: class MyClass {
var publicField: Int = 0
val person = Person()
private var privateField: Int?
} Constant values in the companion object should be written in uppercase, with an underscore separating words: companion object {
const val THE_ANSWER = 42
} Variables & ParametersWritten in lowerCamelCase. Single character values must be avoided, except for temporary looping variables. MiscIn code, acronyms should be treated as words. For example: BAD: XMLHTTPRequest
URL: String?
findPostByID GOOD: XmlHttpRequest
url: String
findPostById DeclarationsVisibility ModifiersOnly include visibility modifiers if you need something other than the default of public. BAD: public val wideOpenProperty = 1
private val myOwnPrivateProperty = "private" GOOD: val wideOpenProperty = 1
private val myOwnPrivateProperty = "private" Access Level ModifiersAccess level modifiers should be explicitly defined for classes, methods and member variables. Fields & VariablesPrefer single declaration per line. GOOD: username: String
twitterHandle: String ClassesExactly one class per source file, although inner classes are encouraged where scoping appropriate. Data Type ObjectsPrefer data classes for simple data holding objects. BAD: class Person(val name: String) {
override fun toString() : String {
return "Person(name=$name)"
}
} GOOD: data class Person(val name: String) Enum ClassesEnum classes without methods may be formatted without line-breaks, as follows: private enum CompassDirection { EAST, NORTH, WEST, SOUTH } SpacingSpacing is especially important in raywenderlich.com code, as code needs to be easily readable as part of the tutorial. IndentationIndentation is using spaces - never tabs. BlocksIndentation for blocks uses 2 spaces (not the default 4): BAD: for (i in 0..9) {
Log.i(TAG, "index=" + i)
} GOOD: for (i in 0..9) {
Log.i(TAG, "index=" + i)
} Line WrapsIndentation for line wraps should use 4 spaces (not the default 8): BAD: val widget: CoolUiWidget =
someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line) GOOD: val widget: CoolUiWidget =
someIncrediblyLongExpression(that, reallyWouldNotFit, on, aSingle, line) Line LengthLines should be no longer than 100 characters long. Vertical SpacingThere should be exactly one blank line between methods to aid in visual clarity and organization. Whitespace within methods should separate functionality, but having too many sections in a method often means you should refactor into several methods. CommentsWhen they are needed, use comments to explain why a particular piece of code does something. Comments must be kept up-to-date or deleted. Avoid block comments inline with code, as the code should be as self-documenting as possible. Exception: This does not apply to those comments used to generate documentation. SemicolonsSemicolons BAD: val horseGiftedByTrojans = true;
if (horseGiftedByTrojans) {
bringHorseIntoWalledCity();
} GOOD: val horseGiftedByTrojans = true
if (horseGiftedByTrojans) {
bringHorseIntoWalledCity()
} Getters & SettersUnlike Java, direct access to fields in Kotlin is preferred. If custom getters and setters are required, they should be declared following Kotlin conventions rather than as separate methods. Brace StyleOnly trailing closing-braces are awarded their own line. All others appear the same line as preceding code: BAD: class MyClass
{
fun doSomething()
{
if (someTest)
{
// ...
}
else
{
// ...
}
}
} GOOD: class MyClass {
fun doSomething() {
if (someTest) {
// ...
} else {
// ...
}
}
} Conditional statements are always required to be enclosed with braces, irrespective of the number of lines required. BAD: if (someTest)
doSomething()
if (someTest) doSomethingElse() GOOD: if (someTest) {
doSomething()
}
if (someTest) { doSomethingElse() } When StatementsUnlike BAD: when (anInput) {
1 -> doSomethingForCaseOneOrTwo()
2 -> doSomethingForCaseOneOrTwo()
3 -> doSomethingForCaseThree()
} GOOD: when (anInput) {
1, 2 -> doSomethingForCaseOneOrTwo()
3 -> doSomethingForCaseThree()
else -> println("No case satisfied")
} TypesAlways use Kotlin's native types when available. Kotlin is JVM-compatible so [TODO: more info] Type InferenceType inference should be preferred where possible to explicitly declared types. BAD: val something: MyType = MyType()
val meaningOfLife: Int = 42 GOOD: val something = MyType()
val meaningOfLife = 42 Constants vs. VariablesConstants are defined using the Tip: A good technique is to define everything using Companion Objects** TODO: A bunch of stuff about companion objects ** Nullable TypesDeclare variables and function return types as nullable with Use implicitly unwrapped types declared with When naming nullable variables and parameters, avoid naming them like When accessing a nullable value, use the safe call operator if the value is only accessed once or if there are many nullables in the chain: editText?.setText("foo") XML GuidanceSince Android uses XML extensively in addition to Kotlin and Java, we have some rules specific to XML. These can be found in our Java code standards LanguageUse |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论