CodeGym /課程 /Kotlin SELF /OOP start common mistakes: mutability, references, respon...

OOP start common mistakes: mutability, references, responsibility, naming

Kotlin SELF
等級 30, 課堂 4
開放

1. Introduction

When you start writing classes for the first time, the brain often pulls a sneaky trick: “Oh, now I have my own types — so I can stuff into them everything I see and change it however I want.” It sounds logical… right up until the first bug, when the total suddenly becomes negative, an expense title “changes by itself”, and the list() method starts printing to the console in the most unexpected places. Today we’ll go through typical OOP-start pitfalls — so you step on them a bit less often, and at least consciously.

Let’s agree on the context: we continue our console mini-project for expense tracking (let’s call it BudgetBuddy). We have an expense entity Expense and a list MutableList<Expense> where we add items and build reports.

2. Mutability: when var turns code into jelly

Usually the very first “bad habit” in OOP looks like this: you see that properties can be declared as var, and your hand automatically writes var everywhere. Because “what if I need to change it later.” The result is a class that can be accidentally modified from anywhere, like clay: press a bit — and the shape is different. The problem is not that var is evil; the problem is that uncontrolled mutability makes program behavior unpredictable, especially when there are many objects and they live in collections.

Too many var: “just in case” is the most expensive argument

Let’s start with an illustration. Here is a “suspicious” version of the expense model:

class Expense(var title: String, var amount: Int, var category: String)

fun main() {
    val e = Expense("Coffee", 300, "food")
    e.amount = -10
    println(e.amount) // -10
}

The code compiles, everything is fair. But from the domain point of view, “expense = -10” sounds like an “anti-expense”, a “credit from the universe”, or simply a bug. If the class allows writing an invalid value, then correctness of the state is held by programmer discipline (and programmer discipline usually runs out at the second coffee).

A healthier default for a starter model is to make properties immutable (val) until you know for sure what you will change and why:

class Expense(val title: String, val amount: Int, val category: String)

fun main() {
    val e = Expense("Coffee", 300, "food")
    println("${e.title}: ${e.amount}") // Coffee: 300
}

This doesn’t make the program “perfect”, but it greatly reduces the number of places where chaos can appear: the object is stable after creation, which makes it easier to “read”.

val protects the reference, not the internals

There is another trap. Many people think: “OK, then I’ll store everything in val, and everything will become immutable.” But val for an object forbids reassigning the reference, not modifying the object (if the object has var properties). The same applies to collections: val protects the variable from reassignment, but does not make the collection “frozen”. This is clearly visible with the standard library: a val list can be modified if it is a MutableList.

fun main() {
    val expenses = mutableListOf<String>()
    expenses.add("Coffee")
    expenses.add("Taxi")

    println(expenses) // [Coffee, Taxi]

    // expenses = mutableListOf() // not allowed; that is the point of val
}

That’s why it helps to keep a simple table in mind (it saves nerves):

What you write What it means What remains “mutable”
val x = ...
you cannot reassign x the inner object may change if it has var
var x = ...
you can reassign x plus the inner object can also change
val list = mutableListOf(...)
you cannot replace the list with another one but you can add/remove because the list is mutable

Rule: val by default, var when necessary

When you write a model, try to say this phrase in your head: “Does this thing change in real life?”

An expense title usually doesn’t change (if the user made a mistake, more often it’s a different operation: “fix input”, but that’s a separate action). The amount is also usually fixed. The category sometimes changes, but that is an explicit “reclassify” scenario. So you can start with val, and for the rare change scenario, make a separate method that performs validation and changes exactly what is needed.

Here is an example where exactly one field is mutable, and the change goes through a method:

class Expense(val title: String, val amount: Int, var category: String) {

    fun recategorize(newCategory: String) {
        val prepared = newCategory.trim()
        if (prepared.isBlank()) return
        category = prepared.lowercase()
    }
}

fun main() {
    val e = Expense("Taxi", 1200, "transport")
    e.recategorize("  Travel  ")
    println(e.category) // travel
}

Note: we are not discussing “advanced property protection” right now (accessors, private set, etc.) — those are separate topics. The key idea here is simple: if an object changes, let it change predictably, through methods that enforce minimal correctness rules.

3. Shared references: one object, two names, and three problems

The second big beginner mistake is forgetting that a variable of an object type stores a reference. You have seen this already, but now the problem becomes practical: the object is in a list, multiple variables refer to it, you change a field somewhere — and suddenly something “breaks” in a completely different place. This is not mysticism; it is ordinary reality of reference types.

Mental model: an “object table” and reference arrows

It helps to imagine it like this: somewhere there is an object Expense(...), and variables are arrows pointing to it.

flowchart LR
    a[val a] --> O["Expense(title='Coffee', amount=300)"]
    b[val b] --> O

If the object is mutable, a change through any arrow changes the same single object.

Example: why it changed “not there”

class Box(var value: Int)

fun main() {
    val a = Box(10)
    val b = a

    b.value = 99

    println(a.value) // 99
}

From the JVM point of view there is one Box object and two variables that point to it. The mistake appears when you expected b = a to “create a copy”. No — a copy is created only by explicitly creating a new object Box(...).

How it breaks collections of objects

Now let’s move the same idea to a list of expenses. Imagine you found an expense by index, stored it in a variable, and later changed it somewhere. If the object is mutable, you changed the list element (because the list holds a reference to the same object).

class Expense(var title: String, var amount: Int)

fun main() {
    val expenses = mutableListOf(
        Expense("Coffee", 300),
        Expense("Taxi", 1200)
    )

    val first = expenses[0]
    first.amount = 999

    println(expenses[0].amount) // 999
}

Sometimes that is exactly what you need. But more often at the beginning you catch “side effects”: you changed something in one place — it showed up in another, and debugging becomes hard.

val does not remove shared references

val does not remove shared references. val only says: “this variable cannot be redirected to another object.” But if the object has var inside, the state still changes. So if you want fewer surprises, two simple paths usually work best early on.

  • First path — make the model more immutable (more val, fewer var), so even with shared references there is nothing to “accidentally change”.
  • Second path — if you need an “independent” object, create a new object explicitly, without hoping for “copy by assignment”.
class Expense(val title: String, val amount: Int)

fun main() {
    val original = Expense("Coffee", 300)
    val independent = Expense(original.title, original.amount)

    println(original === independent) // false
}

We are not using special “model copying” mechanisms yet — keep the idea simple: a new object appears only via ClassName(...).

4. Responsibility: a model without readln() and println()

Another typical OOP-start mistake is to make a class “the god of everything”: it stores data, reads input, draws menus, prints reports. At first it feels convenient: “well, it’s all about expenses.” Then the class grows, and any change becomes open-heart surgery without anesthesia.

Symptom: “the class knows about the console”

Here is a suspicious example (it works, but it starts pulling the project in the wrong direction):

class Expense(val title: String, val amount: Int) {
    fun printLine() {
        println("$title: $amount")
    }
}

fun main() {
    val e = Expense("Coffee", 300)
    e.printLine() // Coffee: 300
}

Why is this a problem? Because Expense now “knows how to print”. And if tomorrow you want output not to the console, but to a string (for a report), or to a file, or to a GUI — the model becomes inconvenient. It starts depending on the display method.

It is much more flexible when the model describes what it is, and output is separate logic (even if for now it lives in main or a utility function).

class Expense(val title: String, val amount: Int)

fun formatExpense(e: Expense): String {
    return "${e.title}: ${e.amount}"
}

fun main() {
    val e = Expense("Coffee", 300)
    println(formatExpense(e)) // Coffee: 300
}

This way Expense stays “clean”: it knows nothing about the console, input, or how you want to present the data.

The model should not “ask the user”

Sometimes beginners do this: “let Expense itself ask the user for the title and amount.” It looks like saving code, but in practice it mixes layers: the model (data) and the UI (input/output) become the same thing, and changes become painful.

Better: main (or your scenario functions) reads input, validates it, and creates the object. The object should not run around the room with a microphone asking “how much did you spend?”.

5. Names: why Item, Data, Info are fog

At the start of OOP there is a desire to name everything as “universally” as possible: Item, Entity, Data, Record. It seems “more professional”. In reality it is like labeling moving boxes “stuff” and “more stuff”, and then looking for your laptop charger. In programming, names are part of the interface, not decoration.

Bad names make code longer

Let’s compare two variants. The first is “universal”:

class Item(val a: String, val b: Int)

fun main() {
    val x = Item("Coffee", 300)
    println(x.a) // Coffee
    println(x.b) // 300
}

The second is domain-oriented:

class Expense(val title: String, val amount: Int)

fun main() {
    val e = Expense("Coffee", 300)
    println(e.title)  // Coffee
    println(e.amount) // 300
}

In the second variant the brain does not do extra work. You read the code and understand the meaning without additional “translation”: amount is an amount, not “some b”.

Short and clear is better than short and unclear

Clarity does not have to be long. title, amount, category — short and clear. But t, a, c is a riddle. In a small learning project it is tolerable, but as soon as you have 5–10 functions and a list of objects — riddles start eating time.

6. Mini refactoring of BudgetBuddy without “architecture for architecture’s sake”

Now let’s gather all ideas into one small, down-to-earth piece of code: an expense model + a few operations on the list. We are not building “perfect architecture”, not introducing new language constructs, and not turning the project into enterprise. We are simply removing typical OOP-start mistakes.

Model: minimum mutability, maximum clarity

class Expense(val title: String, val amount: Int, val category: String)

fun createExpense(titleInput: String, amount: Int, categoryInput: String): Expense? {
    val title = titleInput.trim()
    val category = categoryInput.trim().lowercase()

    if (title.isBlank()) return null
    if (amount <= 0) return null
    if (category.isBlank()) return null

    return Expense(title = title, amount = amount, category = category)
}

We made a simple factory function that returns Expense?: either a valid object, or null if the data is bad. This is the familiar “read → prepare → validate” pattern from the early days of the course, only now the result is an object.

List: val on the collection, operations via functions

It is important to remember: val on a mutable collection protects the reference from reassignment, which is useful for predictability.

fun addExpense(expenses: MutableList<Expense>, e: Expense) {
    expenses.add(e)
}

fun totalAmount(expenses: List<Expense>): Int {
    return expenses.sumOf { it.amount }
}

fun main() {
    val expenses = mutableListOf<Expense>()

    addExpense(expenses, Expense("Coffee", 300, "food"))
    addExpense(expenses, Expense("Taxi", 1200, "transport"))

    println(totalAmount(expenses)) // 1500
}

Here we have no “combine-harvester class”. The model is separate, operations over the collection are separate, and main is the place where the scenario is wired together.

Protection from shared references through design

Now Expense is fully immutable. This means: even if you have a thousand references to the same expense object (which is suspicious by itself, but let’s assume), there is nothing to “accidentally modify”. You either create a new expense, or work with the existing one as a fact.

If you know for sure that an expense must change (for example, the category changes by a user command), do the change via a method, and let the method decide what is allowed.

7. Typical OOP-start mistakes

Mistake 1: “make everything var, because it might be useful later”.
You buy yourself freedom “later”, but pay for it with chaos “now”: any piece of code can change the object, and it becomes hard to prove where exactly it happened. Early on, it is safer to write val in properties by default and add var only for a concrete change scenario, preferably via a separate method with checks.

Mistake 2: forgetting that assignment copies the reference, not creating a new object.
The moment you do b = a does not create a clone. It is just a second name for the same object. If the object is mutable, a change through a will be visible through b, and vice versa. The cure is not “magic”, but discipline: either make objects more immutable, or explicitly create a new object when you need an independent instance.

Mistake 3: storing an entity as a set of parallel variables and lists.
When you have titles, amounts, categories, sooner or later you get desynchronization: you removed an element from one list, forgot to remove it from another, and now “taxi costs 300, and coffee costs 1200”. One list of objects (MutableList<Expense>) solves this at the data-structure level.

Mistake 4: making the model responsible for input and output.
The Expense class should not read readln() or print println() — not because “it’s forbidden”, but because you lose flexibility: the model starts to depend on a specific UI (the console). It’s better to keep input/output in scenarios (main and functions around it), and keep the model as a description of data and simple change rules.

Mistake 5: unclear names (Data, Item, Info, a/b/c).
A “universal” name often means only one thing: you don’t want to think about meaning right now. But you will have to invent the meaning anyway — just later, during debugging. Good names save time when reading code, and reading time in real development is usually more expensive than writing time.

Mistake 6: trying to “treat” the shared-reference problem with extra var and variable shuffling.
When you notice unexpected changes, it is tempting to “move the object to another variable” and hope it gets better. But the problem is not the variable; it is that you have one object and many references to it. If you need an independent instance — create a new object. If you don’t need independence — make changes centralized and predictable.

1
任務
Kotlin SELF, 等級 30, 課堂 4
上鎖
清晰的支出
清晰的支出
1
任務
Kotlin SELF, 等級 30, 課堂 4
上鎖
以複本套用折扣
以複本套用折扣
1
任務
Kotlin SELF, 等級 30, 課堂 4
上鎖
共用參照
共用參照
1
任務
Kotlin SELF, 等級 30, 課堂 4
上鎖
無需控制台的報表
無需控制台的報表
1
問卷/小測驗
類別與物件,等級 30,課堂 4
未開放
類別與物件
類別與物件
留言
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION