Search code examples
androidreactjskotlinandroid-jetpack-composekotlin-multiplatform

Naming Unit @Composable functions as entities


Accorking to doc: https://github.com/androidx/androidx/blob/androidx-main/compose/docs/compose-api-guidelines.md#naming-unit-composable-functions-as-entities

Jetpack Compose framework development and Library development MUST name any function that returns Unit and bears the @Composable annotation using PascalCase, and the name MUST be that of a noun, not a verb or verb phrase, nor a nouned preposition, adjective or adverb. Nouns MAY be prefixed by descriptive adjectives. This guideline applies whether the function emits UI elements or not.

App development SHOULD follow this same convention.

Why

Composable functions that return Unit are considered declarative entities that can be either present or absent in a composition and therefore follow the naming rules for classes. A composable's presence or absence resulting from the evaluation of its caller's control flow establishes both persistent identity across recompositions and a lifecycle for that persistent identity. This naming convention promotes and reinforces this declarative mental model.

Please explain the WHY part.


Solution

  • The reason is that they are very much like a constructor in effect and the standard in Kotlin is to capitalize the first letter of functions that act like constructors even if they are not constructors.

    That is, when you say,

    Button(...) {
      Text("Hello")
    }
    

    you imply that you are creating a button and some text to go into the button.

    The reason you should use nouns, not verbs, is the name should make clear what is being created as a result of the calling the composable function. It is describing a thing, not an action, so the name should be a noun.

    The use of nouns reenforces the declarative nature of the framework because you are declaring what UI should be created (or updated) by composition, not a method to create it. The name of the function should be the the name of the thing it is declared to create and therefore should be a noun.