可读性

This chapter discusses considerations about API consistency and provides the following recommendations:

API consistency

A consistent and well-documented API is crucial for a good development experience. The same is valid for argument order, overall naming scheme, and overloads. Also, it’s worth documenting all conventions.

For example, if one of your methods accepts offset and length as parameters, then so should other methods, instead of, for example, accepting startIndex and endIndex. Parameters like these are most likely of Int or Long type, and thus it’s very easy to confuse them.

The same works for parameter order: Keep it consistent between methods and overloads. Otherwise, users of your library might incorrectly guess the order they should pass arguments in.

Here is an example that preserves the parameter order and uses consistent naming:

  1. fun String.chop(length: Int): String = substring(0, length)
  2. fun String.chop(length: Int, startIndex: Int) =
  3. substring(startIndex, length + startIndex)

If you have many lookalike methods, name them consistently and predictably. This is how the stdlib API works: There are methods first() and firstOrNull(), single() and singleOrNull(), and so on. It’s clear from their names that they are all pairs, and some of them might return null while others might throw an exception.

Use a builder DSL

“Builder” is a well-known pattern in development. It allows you to build a complex entity not in a single expression, but gradually while getting more information. When you need to use a builder, it’s better to write it using a builder DSL, which is binary-compatible and more idiomatic.

A canonical example of a Kotlin builder DSL is kotlinx.html. Consider the following example:

  1. header("modal-card-head") {
  2. p("modal-card-title") {
  3. +book.book.name
  4. }
  5. button(classes = "delete") {
  6. attributes["aria-label"] = "close"
  7. attributes["_"] = closeModalScript
  8. }
  9. }

It could be implemented as a traditional builder, but that would be considerably more verbose:

  1. headerBuilder()
  2. .addClasses("modal-card-head")
  3. .addElement(
  4. pBuilder()
  5. .addClasses("modal-card-title")
  6. .addContent(book.book.name)
  7. .build()
  8. )
  9. .addElement(
  10. buttonBuilder()
  11. .addClasses("delete")
  12. .addAttribute("aria-label", "close")
  13. .addAttribute("_", closeModalScript)
  14. .build()
  15. )
  16. .build()

This implementation has too many details that you don’t necessarily need to know, and it requires you to build each entity at the end.

The situation gets even worse if you need to generate a builder’s content dynamically in a loop. In this scenario, you have to instantiate a variable and dynamically overwrite it:

  1. var buttonBuilder = buttonBuilder()
  2. .addClasses("delete")
  3. for ((attributeName, attributeValue) in attributes) {
  4. buttonBuilder = buttonBuilder.addAttribute(attributeName, attributeValue)
  5. }
  6. buttonBuilder.build()

Inside the builder DSL, you can directly call a loop and all necessary DSL calls:

  1. div("tags") {
  2. for (genre in book.genres) {
  3. span("tag is-rounded is-normal is-info is-light") {
  4. +genre
  5. }
  6. }
  7. }

Keep in mind that inside curly braces it’s impossible to check at compile time whether you have set all the required attributes. To avoid this, pass required arguments as function arguments, not as builder’s properties. For example, if you want href to be a mandatory HTML attribute, your function will look like:

  1. fun a(href: String, block: A.() -> Unit): A

And not just:

  1. fun a(block: A.() -> Unit): A

Builder DSLs are backward-compatible as long as you don’t delete anything from them. Typically this isn’t a problem, because most developers only add more properties to their builder classes over time.

可读性 - 图1

Use constructor-like functions where applicable

Sometimes, you can simplify your API’s appearance by using constructor-like functions. A constructor-like function is a function whose name starts with a capital letter, so it looks like a constructor. This approach can make your library easier to understand.

Suppose you want to introduce an Option type in your library:

  1. sealed interface Option<T>
  2. class Some<T : Any>(val t: T) : Option<T>
  3. object None : Option<Nothing>

You can define implementations of all the Option interface methods – map(), flatMap(), and so on. However, each time your API users create such an Option, they must write extra logic to check what they create. For example:

  1. fun findById(id: Int): Option<Person> {
  2. val person = db.personById(id)
  3. return if (person == null) None else Some(person)
  4. }

To save your users from having to write the same check each time, you can add just one line to your API:

  1. fun <T> Option(t: T?): Option<out T & Any> =
  2. if (t == null) None else Some(t)
  3. // Usage of the code above:
  4. fun findById(id: Int): Option<Person> = Option(db.personById(id))

Now, creating a valid Option is as simple as can be: Just call Option(x) and you have a null-safe, purely functional Option idiom.

Another use case for using a constructor-like function is when you need to return “hidden” things, such as a private instance or an internal object. For example, let’s look at a method from the standard library:

  1. public fun <T> listOf(vararg elements: T): List<T> =
  2. if (elements.isNotEmpty()) elements.asList() else emptyList()

In the code above, emptyList() returns the following:

  1. internal object EmptyList : List<Nothing>, Serializable, RandomAccess

You can write a constructor-like function to lower the cognitive complexity of your code and reduce the size of your API:

  1. fun <T> List(): List<T> = EmptyList
  2. // Usage of the code above:
  3. public fun <T> listOf(vararg elements: T): List<T> =
  4. if (elements.isNotEmpty()) elements.asList() else List()

Use member and extension functions appropriately

Write only the very core of the API as member functions, and everything else as extension functions. This will help you clearly show to the reader what is the core functionality and what isn’t.

For example, consider the following class for a graph:

  1. class Graph {
  2. private val _vertices: MutableSet<Int> = mutableSetOf()
  3. private val _edges: MutableMap<Int, MutableSet<Int>> = mutableMapOf()
  4. fun addVertex(vertex: Int) {
  5. _vertices.add(vertex)
  6. }
  7. fun addEdge(vertex1: Int, vertex2: Int) {
  8. _vertices.add(vertex1)
  9. _vertices.add(vertex2)
  10. _edges.getOrPut(vertex1) { mutableSetOf() }.add(vertex2)
  11. _edges.getOrPut(vertex2) { mutableSetOf() }.add(vertex1)
  12. }
  13. val vertices: Set<Int> get() = _vertices
  14. val edges: Map<Int, Set<Int>> get() = _edges
  15. }

This class contains a bare minimum of vertices and edges as private variables, functions to add vertices and edges, and accessor functions that return an immutable representation of the current state.

You can add all the remaining functionality outside the class:

  1. fun Graph.getNumberOfVertices(): Int = vertices.size
  2. fun Graph.getNumberOfEdges(): Int = edges.size
  3. fun Graph.getDegree(vertex: Int): Int = edges[vertex]?.size ?: 0

Only properties, overrides, and accessors should be members.

Avoid using Boolean arguments in functions

Ideally, a reader should be able to tell the purpose of a function argument just by reading code. With Boolean arguments, however, this is almost impossible to do, especially if you’re not using an IDE (for example, if you’re reviewing the code in a version control service). Using named arguments can help clarify the purpose of arguments, but for now there is no way to force developers to use them in IDEs. Another option is to create a function that contains the action of the Boolean argument and give this function a descriptive name.

For example, in the standard library there are two functions for map():

  1. fun map(transform: (T) -> R): List<R>
  2. fun mapNotNull(transform: (T) -> R?): List<R>

It was possible to add something like map(filterNulls: Boolean) and write code like this:

  1. listOf(1, null, 2).map(false) { it.toString() }

From reading this code, it’s difficult to infer what false refers to. However, if you use the mapNotNull() function, readers will be able to understand the logic at a glance:

  1. listOf(1, null, 2).mapNotNull { it.toString() }

What’s next?

Learn about APIs’: