Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 134 ยท Classes and Objects

Encapsulation and Design

Design safer Kotlin classes: protect invariants with private setters, private constructors and factory functions, avoid leaking mutable state, and hide implementations behind interfaces.

Encapsulation is often explained as "make fields private". That is the mechanism, not the point. The point is protecting rules. A BankAccount has a rule: the balance never goes below zero. A Percentage has a rule: it lies between 0 and 100. If any code anywhere can break those rules, then every line that uses the object must double-check them, and sooner or later one forgets. If the class itself guarantees the rules (an invariant), the rest of the program can simply rely on them.

You already know the tools: visibility modifiers, properties with private setters, constructors and data classes. This lesson turns them into a design approach: guard state, make objects hard to misuse, prefer immutability, create objects through validated factories, never leak mutable internals, and hide implementation classes behind interfaces.

Guard state behind behavior

Public mutable fields invite misuse. Compare these two accounts:

Kotlin Letting the class defend its own rule

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The only way to change balance is through deposit and withdraw, and both check their rules first. Note the two different checks: require blames the caller for a bad argument (IllegalArgumentException), check reports a bad state of the object (IllegalStateException). See require, check and assert. Now see what the compiler does when someone tries a shortcut:

Kotlin Bypassing the rules does not compile (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The message is error: cannot access 'balance': it is private in 'Account'. A mistake that would be a silent bug in many languages is caught at compile time.

Make illegal states unrepresentable

Even better than checking a rule on every call is to design the type so that a broken state cannot exist at all. If a Percentage can only be created with a value from 0 to 100, every function that takes a Percentage is spared the check. The recipe is a private constructor plus a factory function in the companion object:

Kotlin A private constructor and a validating factory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Callers cannot bypass of, because the constructor is private:

Kotlin Calling a private constructor (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler answers error: cannot access 'constructor(value: Int): Percentage': it is private in 'Percentage'. Factories have two other benefits over constructors: they can have meaningful names (Duration.ofMinutes(5), Color.fromHex("#ff8800")), and they can return a different type, such as a cached instance, a subclass or a sealed result instead of throwing.

Returning a result instead of throwing

For input that comes from outside the program (a form, a file), invalid values are normal, not exceptional. A factory that returns null or a Result forces the caller to deal with the failure:

Kotlin Parse, don't validate: a factory that returns a Result

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The idea, sometimes summarized as "parse, don't validate", is to convert loose input into a precise type once, at the boundary, and use that type everywhere inside. This example also combines two earlier lessons: a value class gives the type zero overhead, and Result carries the outcome.

Prefer immutability

An immutable object cannot be left in a broken state, can be shared freely between threads, and is safe as a map key. In Kotlin that means val properties and read-only types. Instead of changing the object, you create a modified copy:

Kotlin An immutable class with copy-style methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Each operation returns a new Cart, and the old one stays valid, which makes undo, comparison and safe sharing trivial. (lines + (...) copies a small map; for very large collections a persistent data structure library or a mutable builder inside a function is more efficient. Measure before you worry.)

For data classes, beware: a data class Age private constructor(val years: Int) still gets a public copy, so Age.of(3).copy(years = -5) happily creates an invalid object (we ran it: it prints Age(years=-5)). The annotation @ConsistentCopyVisibility on the class makes copy as private as the constructor, and then the same call fails with error: cannot access 'fun copy(years: Int = ...): Age': it is private in 'Age'. If invariants matter, use that annotation, an ordinary class with explicit methods, or a data class with a public constructor that validates in init.

Do not leak mutable state

Making a field private is not enough if a public function hands out the mutable object itself. The caller then holds a remote control to your internals:

Kotlin A leaking getter versus a defensive copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Three levels of protection exist, from cheap to safe: return the read-only interface type (List<String>; caller cannot add, but a cast could), return a copy (toList(); safe, costs time per call), or keep the internal collection immutable. The same applies to incoming mutable arguments: if a constructor receives a list and stores it, the caller can still change it later, so copy it on the way in (members = initial.toList()).

Hide the implementation behind an interface

A private or internal class can be the implementation while only an interface (and a factory function) is public. Callers cannot depend on details that are not visible:

Kotlin A public interface, a private implementation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Later you can swap the generator for a random or database-backed one without touching any caller. The same mechanism makes code easy to test: pass a fake implementation of the interface (see Test Doubles). Between files and modules, internal gives a similar boundary for a whole module.

Design guidelines

  • Start with the narrowest visibility that works (private), and widen only when needed.
  • Prefer val over var; if you need change, give the class a method with a verb name (deposit) and not a bare setter.
  • Make objects valid from the first moment: validate in init or in a factory, never leave "create now, configure later" objects when you can avoid them.
  • "Tell, don't ask": instead of reading a field to decide what to do with it, give the object the behavior (account.withdraw(30) rather than account.balance -= 30 after your own checks).
  • Do not expose mutable collections; expose read-only types or copies.
  • Encapsulation is not about secrecy. It is about limiting the number of places that can break a rule to one.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main purpose of encapsulation?

    Visibility and controlled access let a class guarantee its invariants, so other code can rely on them.
  2. 2. What does var balance: Int = 0 followed by private set give you?

    The getter keeps the property's visibility (public), the setter is restricted to the class.
  3. 3. Why use a private constructor with a companion factory function?

    Callers cannot bypass the factory, so every instance passed the checks. Factories can also return other types or cached instances.
  4. 4. class T { private val items = mutableListOf<String>(); fun items(): MutableList<String> = items } has which problem?

    The private field is protected, but the public function hands out the same mutable object. Return List<String>, or a copy.
  5. 5. Which exception does require(x > 0) throw when it fails, and what does it blame?

    require checks arguments and throws IllegalArgumentException; check verifies state and throws IllegalStateException.

Summary

  • Encapsulation protects invariants: the class guarantees its rules, so callers do not re-check them.
  • Use private set, behavior methods (deposit, withdraw) and require/check instead of public mutable fields.
  • Make illegal states unrepresentable: private constructor plus a validating factory, or a Result-returning parse function at the boundary.
  • Prefer immutable classes and copy-style methods; for data classes mind the visibility of copy.
  • Never return your mutable internals; return read-only types or copies, and copy mutable arguments on the way in.
  • Hide implementation classes behind public interfaces and factory functions.

Next: Generics