Utility Class Should Be Object

ID

kotlin.utility_class_should_be_object

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Kotlin

Tags

object, utility

Description

Reports a class that holds no instance state and only groups helper functions. In Kotlin such a declaration should be expressed as an object, which provides a single-instance namespace without requiring callers to allocate an instance just to call a function.

Rationale

A utility class with a zero-argument primary constructor, no properties, and only helper functions is effectively a static namespace. Forcing callers to Utils() an instance — or, worse, leaving the class unfocused as to whether it holds state — obscures intent and adds an unnecessary allocation each time the helper is called. Kotlin’s object declaration captures the singleton-namespace semantics directly, makes member access concise (Utils.add(1, 2)), and signals the design intent to readers.

// Bad — utility class
class Math {
    fun add(a: Int, b: Int) = a + b
}

// Good — object declaration
object Math {
    fun add(a: Int, b: Int) = a + b
}

Remediation

Replace class Foo with object Foo. Move any logic that needs per-instance state into a separate class whose name reflects that state. If the class extends a supertype or is intended for subclassing, leave it as a class — the rule excludes those cases.