Improving Code Quality - Session 45: Does Making the End null Solve Everything?
Key point
This presents a design approach to prevent the problem that arises when using null as the termination signal for an Iterator, since it cannot be distinguished from actual data.
Details
In Java or Kotlin's Iterator, calling next() when there are no elements left raises a NoSuchElementException. To prevent this, one can implement a SafeIterator that returns null when there are no elements, allowing code to be written safely without exceptions.
However, this approach has a critical problem. If the collection's elements themselves contain null, it becomes impossible to distinguish between null as data and null as a termination signal. This can cause a bug where the loop ends prematurely even though actual data remains.
There are two main design strategies to solve this problem.
- Restricting types and using explicit types: Restrict the element type to
T : Anyso thatnullcannot be included, or define a separate type such asOptionalorNullableValuethat explicitly represents 'emptiness'. - Defining a dedicated return type: Create a separate return type such as
NextResultto clearly distinguish between the case where an element exists (Exists) and the case where no element exists (NoSuchElement). This allows safe handling without confusing anulldata value with a termination signal.
This summary was generated automatically by AI. Check the original for the author's claims and context. Copyright belongs to the original author.
Our guide explains how the AI works. Report summary errors, attribution issues, or removal requests via Contact.