Share
Embed
Mastering API Visibility in Kotlin (Chicago Kotlin Users Group 2021 August)
When designing a library, minimizing your API surface - the types, methods, properties, and functions you expose to the outside world - is a great idea. This doesn't apply to just libraries: it's a consideration you should make for every module in a multi-module project. In this talk, we'll look at all the ways that Kotlin lets you get your visibility just right.
Resources and more: https://zsmb.co/talks/mastering-api-visibility/
Márton Braun
August 12, 2021
Transcript
143 slides
-
Minimal APIs Item 15: Minimize the accessibility of classes and
members Chapter 4: Classes and Interfaces -
Minimal APIs › Easier to maintain and change public fun
Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", ), Minimal APIs › Easier to
maintain and change @Deprecated( message = "Use a chained .validate {} call instead", level = DeprecationLevel.WARNING, ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", ), Minimal APIs › Easier to
maintain and change @Deprecated( message = "Use a chained .validate {} call instead", level = DeprecationLevel.WARNING, ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", ), Minimal APIs › Easier to
maintain and change @Deprecated( message = "Use a chained .validate {} call instead", level = DeprecationLevel.WARNING, ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change @Deprecated( message
= "Use a chained .validate {} call instead", level = DeprecationLevel.WARNING, replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", imports = arrayOf("com.example.validate"), ), ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change @Deprecated( message
= "Use a chained .validate {} call instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", imports = arrayOf("com.example.validate"), ), ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change @Deprecated( message
= "Use a chained .validate {} call instead", level = DeprecationLevel.ERROR, replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", imports = arrayOf("com.example.validate"), ), ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change @Deprecated( message
= "Use a chained .validate {} call instead", level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", imports = arrayOf("com.example.validate"), ), ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change @Deprecated( message
= "Use a chained .validate {} call instead", level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith( "this.stringPref(key).validate(isValid)", imports = arrayOf("com.example.validate"), ), ) public fun Krate.stringPref( key: String, isValid: (newValue: String) -> Boolean, ) -
Minimal APIs › Easier to maintain and change › Easier
to learn › Harder to misuse -
Internal visibility public interface Service { fun createUser(): User }
internal class NetworkService : Service { override fun createUser(): User { ... } } -
Internal visibility public class NetworkClient { public var state: State
= Disconnected internal set public fun connect() { state = Connected } } -
@Test fun verifyState() { assertEquals(expectedState, state) } Testing @VisibleForTesting(otherwise =
PRIVATE) internal var state: State -
Java interop void repositoryExample() { } class Repository { internal
fun createEntity() { ... } } -
Java interop void repositoryExample() { new Repository().createEntity$examplelibrary(); } class Repository
{ internal fun createEntity() { ... } } -
Java interop void repositoryExample() { new Repository().createEntity$examplelibrary(); } class Repository
{ internal fun createEntity() { ... } } -
class Repository { internal fun createEntity() { ... } }
Java interop @JvmName("pleaseDoNotCallThisMethod") (); void repositoryExample() { new Repository(). } pleaseDoNotCallThisMethod -
Java interop void repositoryExample() { new Repository(). } class Repository
{ internal fun createEntity() { ... } } Cannot resolve method 'createEntity' in 'Repository' @JvmSynthetic (); createEntity -
Explicit API mode › Explicit visibility modifiers for all declarations
› Explicit types for public declarations -
Explicit API mode kotlin { explicitApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions
{ freeCompilerArgs += [ '-Xexplicit-api=strict', ] } } -
Explicit API mode kotlin { explicitApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions
{ freeCompilerArgs += [ '-Xexplicit-api=strict', '-progressive', ] } } -
Explicit API mode kotlin { explicitApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions
{ freeCompilerArgs += [ '-Xexplicit-api=strict', '-progressive', ] } } -
Explicit API mode kotlin { explicitApiWarning() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions
{ freeCompilerArgs += [ '-Xexplicit-api=warning', '-progressive', ] } } -
Explicit API mode class User(var name: String, var age: Int)
{ fun sayHi() { println("Hi, I'm $name") } fun reset() { name = "" age = 0 } } -
Explicit API mode class User(var name: String, var age: Int)
{ fun sayHi() { println("Hi, I'm $name") } fun reset() { name = "" age = 0 } } -
public Explicit API mode public class User(var name: String, var
age: Int) { fun sayHi() { println("Hi, I'm $name") } fun reset() { name = "" age = 0 } } -
Explicit API mode public class User(public var name: String, var
age: Int) { fun sayHi() { println("Hi, I'm $name") } fun reset() { name = "" age = 0 } } public -
Explicit API mode public class User(public var name: String, public
var age: Int) { public fun sayHi() { println("Hi, I'm $name") } fun reset() { name = "" age = 0 } } -
Explicit API mode public class User(public var name: String, public
var age: Int) { public fun sayHi() { println("Hi, I'm $name") } internal fun reset() { name = "" age = 0 } } -
Explicit API mode private val DEFAULT_CLIENT = Client() public interface
ClientFactory { public fun client() = DEFAULT_CLIENT } -
Explicit API mode private val DEFAULT_CLIENT = Client() public interface
ClientFactory { public fun client() = DEFAULT_CLIENT } -
Explicit API mode private val DEFAULT_CLIENT = OfflineClient() public interface
ClientFactory { public fun client() = DEFAULT_CLIENT } -
Explicit API mode private val DEFAULT_CLIENT = OfflineClient() public interface
ClientFactory { public fun client(): Client = DEFAULT_CLIENT } -
Explicit API mode › Explicit visibility modifiers for all declarations
› Explicit types for public declarations -
Explicit API mode › Explicit visibility modifiers for all declarations
› Explicit types for public declarations › Configured per-module -
Explicit API mode › Explicit visibility modifiers for all declarations
› Explicit types for public declarations › Configured per-module › Strict or warning level -
Published API public inline fun song() { secretFunction() } internal
fun secretFunction() { println("through the mountains") } -
Published API public inline fun song() { secretFunction() } internal
fun secretFunction() { println("through the mountains") } fun clientCode() { song() } -
fun clientCode() { } secretFunction() Published API public inline fun
song() { secretFunction() } internal fun secretFunction() { println("through the mountains") } e: Public-API inline function cannot access non-public-API song() -
Published API public inline fun song() { secretFunction() } internal
fun secretFunction() { println("through the mountains") } fun clientCode() { } secretFunction() -
Published API fun clientCode() { } secretFunction() public inline fun
song() { secretFunction() } internal fun secretFunction() { println("through the mountains") } -
Published API fun clientCode() { } song() @PublishedApi public inline
fun song() { secretFunction() } internal fun secretFunction() { println("through the mountains") } -
Published API fun clientCode() { song() secretFunction() } public inline
fun song() { secretFunction() } @PublishedApi internal fun secretFunction() { println("through the mountains") } e: Cannot access 'secretFunction': it is internal -
Published API fun clientCode() { } song() @PublishedApi public inline
fun song() { secretFunction() } internal fun secretFunction() { println("through the mountains") } -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.WARNING, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opt-in APIs package com.example.lib.core @RequiresOptIn( level = RequiresOptIn.Level.ERROR, message =
"This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi @InternalMyLibraryApi public fun coreApi() -
public fun addonFunction() { coreApi() } package com.example.lib.core @RequiresOptIn( level
= RequiresOptIn.Level.ERROR, message = "This is internal API for my library, " + "please don't rely on it." ) public annotation class InternalMyLibraryApi @InternalMyLibraryApi public fun coreApi() core addon Opt-in APIs -
core addon @InternalMyLibraryApi public fun coreApi() Opting in public fun
addonFunction() { coreApi() } -
Opting in tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=com.example.lib.core.InternalMyLibraryApi',
] } } @InternalMyLibraryApi public fun coreApi() public fun addonFunction() { coreApi() } @InternalMyLibraryApi -
Opting in @InternalMyLibraryApi public fun coreApi() public fun addonFunction() {
@OptIn(InternalMyLibraryApi::class) coreApi() } -
Opting in @InternalMyLibraryApi public fun coreApi() public fun addonFunction() {
@OptIn(InternalMyLibraryApi::class) coreApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opting in @InternalMyLibraryApi public fun coreApi() public fun addonFunction() {
@OptIn(InternalMyLibraryApi::class) coreApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opting in @InternalMyLibraryApi public fun coreApi() public fun addonFunction() {
@OptIn(InternalMyLibraryApi::class) coreApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opting in @InternalMyLibraryApi public fun coreApi() @OptIn(InternalMyLibraryApi::class) public fun addonFunction()
{ coreApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
Opting in @InternalMyLibraryApi @JvmSynthetic public fun coreApi() @OptIn(InternalMyLibraryApi::class) public fun
addonFunction() { coreApi() } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { freeCompilerArgs += [ '-Xopt-in=kotlin.RequiresOptIn', ] } } -
core Validating API buildscript { dependencies { classpath 'org.jetbrains.kotlinx:binary-compatibility-validator:0.5.0' }
} apply plugin: 'binary-compatibility-validator' -
core apiValidation { ignoredPackages += [ 'com/getstream/sdk/chat/databinding', 'io/getstream/chat/android/ui/databinding', ] ignoredProjects
+= [ 'stream-chat-android-docs', 'stream-chat-android-sample', 'stream-chat-android-ui-components-sample', 'stream-chat-android-test', ] nonPublicMarkers += [ 'io.getstream.chat.android.core.internal.InternalStreamChatApi', ] } Validating API -
core apiValidation { ignoredPackages += [ 'com/getstream/sdk/chat/databinding', 'io/getstream/chat/android/ui/databinding', ] ignoredProjects
+= [ 'stream-chat-android-docs', 'stream-chat-android-sample', 'stream-chat-android-ui-components-sample', 'stream-chat-android-test', ] nonPublicMarkers += [ 'io.getstream.chat.android.core.internal.InternalStreamChatApi', ] } Validating API -
core apiValidation { ignoredPackages += [ 'com/getstream/sdk/chat/databinding', 'io/getstream/chat/android/ui/databinding', ] ignoredProjects
+= [ 'stream-chat-android-docs', 'stream-chat-android-sample', 'stream-chat-android-ui-components-sample', 'stream-chat-android-test', ] nonPublicMarkers += [ 'io.getstream.chat.android.core.internal.InternalStreamChatApi', ] } Validating API -
core apiValidation { ignoredPackages += [ 'com/getstream/sdk/chat/databinding', 'io/getstream/chat/android/ui/databinding', ] ignoredProjects
+= [ 'stream-chat-android-docs', 'stream-chat-android-sample', 'stream-chat-android-ui-components-sample', 'stream-chat-android-test', ] nonPublicMarkers += [ 'io.getstream.chat.android.core.internal.InternalStreamChatApi', ] } Validating API -
core Validating API public abstract interface class io/getstream/chat/android/client/ChatEventListener { public
abstract fun onEvent (Lio/getstream/chat/android/client/events/ChatEvent;)V } public final class io/getstream/chat/android/client/api/models/AutocompleteFilterObject : io/getstream/chat/android/client/api/models/FilterObject { public final fun component1 ()Ljava/lang/String; public final fun component2 ()Ljava/lang/String; public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/Autocompl eteFilterObject; public fun equals (Ljava/lang/Object;)Z public final fun getFieldName ()Ljava/lang/String; public final fun getValue ()Ljava/lang/String; public fun hashCode ()I public fun toString ()Ljava/lang/String; } gradlew apiDump -
core Validating API Execution failed for task ':stream-chat-android-client:apiCheck'. > API
check failed for project stream-chat-android-client. @@ -218,9 +218,8 @@ public final class io/getstream/chat/android/client/api/models/AutocompleteFilterObject : io/getstream/chat/android/client/api/models/FilterObject { public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/Autocompl eteFilterObject; + public final fun copy (Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/AutocompleteFilterObject; public fun equals (Ljava/lang/Object;)Z public final fun getFieldName ()Ljava/lang/String; public final fun getValue ()Ljava/lang/String; You can run :stream-chat-android-client:apiDump task to overwrite API declarations gradlew apiCheck -
core Validating API Execution failed for task ':stream-chat-android-client:apiCheck'. > API
check failed for project stream-chat-android-client. @@ -218,9 +218,8 @@ public final class io/getstream/chat/android/client/api/models/AutocompleteFilterObject : io/getstream/chat/android/client/api/models/FilterObject { public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/Autocompl eteFilterObject; + public final fun copy (Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/AutocompleteFilterObject; public fun equals (Ljava/lang/Object;)Z public final fun getFieldName ()Ljava/lang/String; public final fun getValue ()Ljava/lang/String; You can run :stream-chat-android-client:apiDump task to overwrite API declarations gradlew apiCheck -
core Validating API Execution failed for task ':stream-chat-android-client:apiCheck'. > API
check failed for project stream-chat-android-client. @@ -218,9 +218,8 @@ public final class io/getstream/chat/android/client/api/models/AutocompleteFilterObject : io/getstream/chat/android/client/api/models/FilterObject { public final fun component1 ()Ljava/lang/String; - public final fun component2 ()Ljava/lang/String; - public final fun copy (Ljava/lang/String;Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/Autocompl eteFilterObject; + public final fun copy (Ljava/lang/String;)Lio/getstream/chat/android/client/api/models/AutocompleteFilterObject; public fun equals (Ljava/lang/Object;)Z public final fun getFieldName ()Ljava/lang/String; public final fun getValue ()Ljava/lang/String; You can run :stream-chat-android-client:apiDump task to overwrite API declarations gradlew apiCheck -
• Mastering API Visibility in Kotlin https://zsmb.co/mastering-api-visibility-in-kotlin/ • Maintaining
Compatibility in Kotlin Libraries https://zsmb.co/maintaining-compatibility-in-kotlin-libraries/ • How to Build Awesome Android Libraries https://zsmb.co/talks/how-to-build-awesome-android-libraries/ • Effective Java, 3rd Edition https://www.amazon.com/Effective-Java-Joshua-Bloch/dp/0134685997 • Effective Kotlin https://leanpub.com/effectivekotlin/ Resources -
Mastering API Visibility in Kotlin zsmb.co/talks zsmb13 Márton Braun ›
Minimal API is nice › Internal visibility › Explicit API mode › Published API › Opt-in APIs