1. Introduction

Kotlin offers a rich set of features that make developers’ lives easier. One such feature is the TODO() function, which serves as a versatile tool for managing placeholders in our code. In this article, we’ll look at the TODO() function, exploring its syntax, use cases, best practices, and advanced techniques to help us harness its power effectively.

2. TODO() Syntax

At its core, the TODO() function is quite simple to use. It’s essentially a function call with an optional message:

TODO() // without a message
TODO("Implement this feature") // with a message

We can place these calls anywhere in our code where we need to indicate that something remains to be done. When it’s executed, the TODO() function throws a NotImplementedError() with our optional message as the cause.

3. Benefits

The primary purpose of TODO() is to act as a placeholder for code that we haven’t implemented yet or need to revisit later. It serves several important functions:

  • Placeholder for Future Code: When we’re working on a project and know that certain parts of the codebase are incomplete or need further attention, we can use TODO() to mark those areas.
  • Documenting Incomplete Code: It serves as documentation within the code, making it clear to us and other developers that specific functionality is missing or needs improvement.
  • Tracking Development Progress: TODO() statements can help us keep track of what needs to be done in a project, allowing for better project management and collaboration.

4. Example

As a simple example, let’s implement a Calculator, but leave add() and subtract() to be implemented in the future:

class Calculator {
    fun add(a: Int, b: Int): Int {
        TODO("Implement a + b")
    }

    fun subtract(a: Int, b: Int): Int {
        TODO("Implement a - b")
    }
}

If we use this implementation anywhere, it’ll throw a NotImplementedError. We’ll need to properly implement the functions and remove the TODO() calls to avoid this error. However, the code will compile, and we’ll be able to run the project and unit tests. For example, we can design a unit test that compiles, but notice that we cannot actually test the functionality yet:

@Test
fun `calculator should add two numbers`() {
    val calculator = Calculator()

    assertThrows<NotImplementedError>("Implement a + b") {
        calculator.add(1, 2)
    }
}

When our function is ready, we can make assertions without changing much of the structure of the test.

5. Conclusion

In the world of software development, simplicity often conceals great utility. The Kotlin TODO() function is a prime example. In this article, we’ve explored its syntax, purpose, and benefits.

The TODO() function, though simple, is a powerful tool for enhancing our Kotlin coding journey. As always, the code used in this article is available over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.