© Peter Späth 2019
Peter SpäthLearn Kotlin for Android Developmenthttps://doi.org/10.1007/978-1-4842-4467-8_6

6. Comments in Kotlin Files

Peter Späth1 
(1)
Leipzig, Germany
 

Comments in computer language files are text that does not belong to the computer language itself and thus have no influence over the program execution, but provide a textual description of elements and constructs used in the program. Comments help the reader to understand your program.

From a technical point of view comments are easy to generate and differentiate from the program syntax itself.
  • Everything starting with a double slash // (not inside a string literal) to the end of the line is a comment.

  • Everything starting with a /* and ending with a */ (both not inside a string literal) is a comment, no matter how many lines are spanned by this.

At first glance, comments might seem like a nice-to-have feature in programs, and adding or omitting them seems to be a personal decision of each developer. There is more to commenting, though. Looking a bit closer at the matter, comments are handled in the realm between two limits:
  • Writing no comments at all: For short programs and those that are extremely well structured and self-explanatory, it is a valid, although arguable position to write no comments at all. The advantages of such an approach are obvious: You have to write less, there is no danger of confusing comments and source code, and following the approach properly will result in comprehensive code of high quality. There are disadvantages as well, though: You might be wrong in your assessment of whether your code is self-explanatory, tools depending on comments do not provide output, or your company’s quality assurance guidelines might get violated.

  • Verbose commenting : On the other hand, if you verbosely comment each and every bit of your program, you will have to write a lot, and you might neglect code quality because ambiguous or confusing constructs in the program are clarified by the comments.

The best approach lies somewhere between these limits. As a rule of thumb, you should write comments for classes, interfaces, and singleton objects, explaining what they are good for, and you should comment public functions in them, including description of their parameters.

Note

I owe you a confession here. The NumberGuess game app from the previous chapters did not contain any comments in the sources I provided. Comments were left out to keep the listings small, and the floating text around those listings serves as a substitute for the reader. After you’ve read this chapter, feel free to remedy this and add appropriate comments to the classes, interfaces, and singleton objects there.

In this chapter we cover exactly how comments should be added to Kotlin files, including what can be done with them.

Package Comments

We learned that packages correspond to files with a strong cohesion of their purpose and functioning. From a technical point of view, each package also corresponds to a directory in the operating system’s file hierarchy.

It makes sense to describe packages through appropriate commenting, and the way we do this in Kotlin is as follows: For each package, that is to say inside each folder, create a file package-info.md. To do this inside Android Studio, you must switch to the Project Files view type in the project explorer (see Figure 6-1). Click the small gray downward-pointing rectangle next to Android to switch the view type. You can then right-click on one of the packages and from the shortcut menu select New ➤ File. Enter the complete file name package-info.md.

Files with the suffix .md are Markdown files. Markdown is a styling language similar to HTML, but with its own simplified syntax. We are going to describe Markdown soon, but first we must teach Android Studio how to handle Markdown files. To do so, double-click one of the new package-info.md files. The Studio opens the file in its standard text editor, but it displays a warning message on top of the edit pane, as shown in Figure 6-2.
../images/476388_1_En_6_Chapter/476388_1_En_6_Fig1_HTML.jpg
Figure 6-1.

Project Files view

../images/476388_1_En_6_Chapter/476388_1_En_6_Fig2_HTML.jpg
Figure 6-2.

The Android Studio trying to open a Markdown file

Click the Install plugins link. On the subsequent screens accept any license declaration, and if asked, select Use markdown support by JetBrains.

Inside each package-info.md file, let the first line read
# Package full.name.of.the.package

where for full.name.of.the.package you substitute the name of each package. The line starting with a single # actually stands for a level 1 heading.

The rest of the file contains Markdown styled text. For example, the package-info.md file inside the package kotlinforandroid.book.numberguess.random could read
# Package kotlinforandroid.book.numberguess.random
This package contains *interfaces* and *classes* for generating random numbers.
In your code you will write something like this:
     val rnd:RandomNumberGenerator = [ one of the 'impl' classes instantiated ]
For example,
     val rnd:RandomNumberGenerator = StdRandom()
     // or
     val rnd:RandomNumberGenerator = RandomRandom()
These package-info.md files and all the other documentation constructs we will talk about here then can be used to generate documentation for your project. During this process the *interface* will be translated to emphasized text, and passages with four spaces at the beginning of the line will have a code style format applied. Text inside backtick quotes (‘) will be marked as inline code. This particular Markdown file, for example, will be translated into a piece of documentation like the one shown in Figure 6-3. These and all the other standard Markdown syntax elements are described in the next section.
../images/476388_1_En_6_Chapter/476388_1_En_6_Fig3_HTML.jpg
Figure 6-3.

Translated Markdown code

Markdown

Both Markdown files as used for package descriptions and inlined documentation inside your Kotlin code files use a common syntax for styling issues. These Markdown syntax elements are described in Table 6-1.
Table 6-1.

Markdown Syntax

Style

Markdown Syntax

Hints

Heading Level 1

# Heading

The package-info.md file must not contain more than one level 1 heading. You can add a # at the end of the header line.

Heading Level 2–6

## Heading

### Heading

The number of # determines the level. You can improve readability by appending the same number of # at the end of the header.

Unordered List

- Item1

- Item2

You could also use + or * as an item indicator.

Ordered List

1. Item1

2. Item2

The consecutive numbering will be assured automatically, so you could write any number (write always “1.” or whatever).

Emphasis

*some text*

or _some text_

If you need an asterisk (*) or underscore (_) in your text, write * or \_.

Strong Emphasis

**some text**

or

_ _some text_ _

If you need an asterisk (*) or underscore (_) in your text, write * or \_.

Block Quote

> some text

You can increase the level by using more > characters at the line beginnings. Block quotes can contain other Markdown elements.

Paragraph Delimiter

<empty line>

A line break at the end of some text will not end a paragraph.

Link

See below

Inlined Code

'some text'

(backticks)

If you need a backtick (‘) in your text, write '.

Block Code

⊔⊔⊔⊔ code line 1

⊔⊔⊔⊔ code line 2

This must be surrounded by empty lines. ⊔ is a space character (you could also use one tab character instead).

Rules

- - -

* * *

You can also use more of these, and use space characters as delimiters.

Escapes

Prepend a ""

Use this to avoid characters doing something special, as described earlier in the table. Eligible characters are * _ [ ] ( ) # + - . ! '

You have several options for inserting links. First you can create an inlined link as follows:
[link text](link-URL)
or
[link text](link-URL "Title")
where the optional "Title" goes to the title attribute in case the documentation gets transformed to HTML. Then the title attribute, for example, gets shown to the user once the mouse hovers over the link (this behavior depends on the browser used). Here is an example for such an inlined link:
Find the link here:
[Link](http://www.example.com/somePage.html "Page")
Reference links use a reference ID so you can refer to the same link several times in a text. The syntax is
[link text][link ID]
where the link ID can contain letters, spaces, numbers, and punctuation, but is otherwise case insensitive. Somewhere else in the text the link definition itself needs to be provided, on a line on its own:
[link ID]: link-URL
or
[link ID]: link-URL "Title"

For long URLs or long titles, the optional "Title" can also be put in the next line. Note that the link definitions do not produce any output, they just make the text in the Markdown file easier to read.

As an abbreviation the link text can serve as both the text and the ID, if you write
[link text][]
and for the definition
[link text]: link-URL
or
[link text]: link-URL "Title"

If you don’t need a link text but just want to tell the URL, you should convert the links to automatic links by surrounding them with angle brackets as in < http://www.apress.com >. The URL then gets printed as is, but is clickable in addition.

As an extension to links as just described, you can refer to classes, properties, and methods as if they were implicit links:
[com.example.TheClass]
[com.example.TheClass.property]
[com.example.TheClass.method]
You can do this the same way for interfaces and singleton objects. If you want to provide your own link text, write this:
[link text][com.example.TheClass]
[link text][com.example.TheClass.property]
[link text][com.example.TheClass.method]

If the element being documented might address classes, interfaces, or singleton objects by their simple name because they have been imported, the package specifier can be omitted and you can directly write [TheClass], [TheClass.property], and [TheClass.method].

Class Comments

We know that multiline comments can be written as /* ... */. As a slight modification, for documenting code elements the convention is to add another asterisk (*) to the left comment bracket: /** ... */, and in addition every line inside the comments is supposed to start with an asterisk as shown here:
/**
 *The comment ...
 * ...
 */

This is still a multiline comment that happens to start with an asterisk, but the tool that knows how to extract the documentation from the code recognizes this as something that needs to be handled. You can still use normal multiline comments /* ... */ at will, but the documentation tool will just ignore them.

Class comments are written just in front of the class ... declaration, as such an adapted multiline comment /** ... */. The content of the class description comment is Markdown code, as described earlier.

The first paragraph of such documentation should provide a short summary, as tools might use it for listings. In addition to standard Markdown elements, in the documentation you can add elements as follows:
  • @param <name> description: Describes a type parameter <name> of the class. Class type parameters are described later in the book. You can also write @param[name] description.

  • @constructor description: Describes the primary constructor of a class.

  • @property <name> description: Describes a parameter of the primary constructor.

  • @sample <specifier>: Inserts the specified function’s code.

  • @see <specifier>: Adds a link to the specified identifier (a class, interface, singleton object, property, or method).

  • @author description: Adds authoring information.

  • @since description: Adds information about how long the documented element has existed (version info, etc.).

  • @suppress: Excludes the class, interface, or singleton object from the documentation.

An example of documentation for class MainActivity of the NumberGuess

game reads like this:
/**
 * The main activity class of the NumberGuess game app.
 * Extends from the
 * [android.support.v7.app.AppCompatActivity]
 * class and is thus compatible with earlier
 * Android versions.
 *
 * The app shows a GUI with the following buttons:
 * - **Start**: Starts the game
 * - **Do Guess**: Used for guessing a number
 *
 * Once started, the game secretly determines a random
 * number the user has to guess. The user performs
 * guesses and gets told if the guessed number is too
 * low, too high, or a hit.
*
 * Once hit, the game is over.
*
 * @see Constants
*
 * @author Peter Späth
 * @since 1.0
 */
class MainActivity : AppCompatActivity() {
    ...
}
The corresponding output, once converted by a documentation tool, would look like Figure 6-4.
../images/476388_1_En_6_Chapter/476388_1_En_6_Fig4_HTML.jpg
Figure 6-4.

Documentation for the NumberGuess activity

Function and Property Comments

For functions and properties, you basically do the same as for classes. Just add /** ... */ in front of any function or property you want to comment. As for class documentation, you start each line with any number of spaces and an asterisk. Inside use Markdown code again. For example:
...
class SomeClass {
    /**
    * This describes property prop
    * ...
    */
    val prop:Int = 7
    /**
     * This describes function func
     * ...
     */
    fun func() {
        ...
     }
}

As for classes, interfaces, and singleton objects, the first paragraph of such documentation should provide a short summary, as tools might use it for listings.

For properties, there are a couple of additional elements you can use:
  • @sample <specifier>: Inserts the specified function’s code.

  • @see <specifier>: Adds a link to the specified identifier (a class, interface, singleton object, property, or method).

  • @author description: Adds authoring information.

  • @since description: Adds information about how long the documented element has existed (version info, etc.).

  • @suppress: Excludes the property from the documentation.

Function documentation snippets should also describe the function’s parameters and return values. In detail, here are all the documentation elements for functions.
  • @param <name> description: Describes a function parameter.

  • @return description: Describes what the function returns.

  • @receiver description: Describes the receiver of an extension function.

  • @throws <specifier>: Indicates that the function might throw the exception designated by the specifier. We cover exceptions later in the book.

  • @exception <specifier>: Same as @throws.

  • @sample <specifier>: Inserts the specified function’s code.

  • @see <specifier>: Adds a link to the specified identifier (a class, interface, singleton object, property, or method).

  • @author description: Adds authoring information.

  • @since description: Adds information about how long the documented element has existed (version info, etc.).

  • @suppress: Excludes the property from the documentation.

Exercise 1

Add comments to all packages, classes, and public functions of the NumberGuess game app.

Generate Your Own API Documentation

With all elements of a program properly documented, we now need to find a way to extract the documentation for creating, for example, a collection of interlinked HTML documents. The generated documentation should describe all classes, interfaces, and singleton objects, as well as all public methods and properties. Because these elements are enough for a client software to know how to interact with your program, such documentation is commonly referred to as application programming interface (API) documentation .

Dokka is a tool Kotlin can use to create exactly this kind of API documentation. To install Dokka, open Android Studio. Inside the Gradle Scripts drawer (you might need to switch back to the Android view type), there are two files named build.gradle, one labeled Project NumberGuess and one labeled Module: app (see Figure 6-5). Those two build files are responsible for describing how the app is to be built to run correctly. This includes declaring libraries that need to be made available to your program.
../images/476388_1_En_6_Chapter/476388_1_En_6_Fig5_HTML.jpg
Figure 6-5.

Build scripts

Note

The term library commonly refers to programs built by others, from which parts get used by your app to perform certain tasks. You’ll very often add libraries to your projects so you can benefit from the work others have made available to the public.

Open the Project build.gradle and add the following line right under buildscript {:
ext.dokka_version = '0.9.17'
In the same file, inside the dependencies block also add (one line):
classpath "org.jetbrains.dokka:
       dokka-android-gradle-plugin:${dokka_version}"

This ensures the Dokka library gets added to the project.

Now open the Moduĺe build.gradle and underneath all the other apply plugin lines, add
apply plugin: 'org.jetbrains.dokka-android'
Inside the same file, add this at the bottom:
task myDokka(type: org.jetbrains.dokka.gradle.
   DokkaAndroidTask) {
    outputFormat = 'html'
    outputDirectory = "dokka"
    includes = ['packages.md']
    doFirst {
        // build the packages.md file
        def pckg = new File(projectDir.absolutePath +
            File.separator + "packages.md")
        pckg.text = ""
        def s = ""
        projectDir.eachFileRecurse(
              groovy.io.FileType.FILES) { f ->
            if(f.name == 'package-info.md') {
                s += " " + f.text
            }
        }
        pckg.text = s
    }
}

This configures Dokka and adds a preparation step.

Note

Dokka by default doesn’t know how to handle our package-info.md files. It instead expects a single file packages.md. The preparation step gathers all package- info.md files and builds a packages.md file. By the way, this little script is written in Groovy, the language on which the Gradle build system relies.

Now to actually perform the documentation generation, open the Gradle tab at the very right edge of the window, then navigate to NumberGuess: ➤ NumberGuess ➤ Tasks ➤ Documentation. Double-click myDokka (see Figure 6-6).
../images/476388_1_En_6_Chapter/476388_1_En_6_Fig6_HTML.jpg
Figure 6-6.

Dokka build task

You’ll now find the API documentation as a collection of interlinked HTML files inside the folder dokka (switch to the Project Files view type to see it inside Android Studio).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.190.167