Share
Explore

Lab module on encapsulation in Kotlin

One of the core pillars of object oriented programming is encapsulation.
Our objects are WALLED GARDENS. The data fields should be private: not accessible outside that class
and readable or mutable only with public getter and setter methods.

Consider the case of a banking application. We would make the bank balance private and we would have a public setter method for the bank balance but it would encode business logic to make sure that the balance was large enough to accommodate the withdrawal that the customer wanted to withdraw.

🛰️ Lab: Encapsulation in Kotlin – Saving the Mars Probe

🧑‍🏫 Story: The $300 Million Mars Miss

In the early days of planetary exploration, the first generation of robotic Mars probes was controlled by procedural C code (pre OO). Everything was global—variables, states, configurations. It was fast to write but dangerous to maintain.
One fateful day, a technician on Earth ran a routine diagnostic to check the radio system while the spacecraft was en route to Mars. The diagnostic inadvertently altered a shared global variable—one that also controlled thruster firing logic. The values were corrupted without anyone realizing, and during its final course correction maneuver… the probe burned too hard and missed Mars entirely.
300 million dollars—gone.
That tragic oversight became a defining case study in why we encapsulate data. Had the variables related to thruster controls been private, accessible only through carefully designed public interfaces (getters/setters), the diagnostic tool would never have been able to corrupt them. That one principle—encapsulation—could have saved the mission.

🧠 What Is Encapsulation?

Encapsulation is a principle of object-oriented programming that protects data by keeping it private inside an object.
Other parts of the program can’t mess with the internal state of an object directly—they must go through controlled access points, like public methods.

🚀 Kotlin Encapsulation Example

🔍 Use Case: Controlling a Spacecraft Thruster

class ThrusterSystem {
// Private variable – cannot be accessed from outside directly
private var fuelLevel: Double = 100.0

fun fireThruster(amount: Double) {
if (amount <= fuelLevel) {
fuelLevel -= amount
println("🔥 Thruster fired using $amount% fuel. Remaining: $fuelLevel%")
} else {
println("⚠️ Not enough fuel!")
}
}

fun checkFuel(): Double {
return fuelLevel
}

fun setFuel(newAmt:Double){
fuelLevel = newAmt
}

// No direct setter: prevents unauthorized fuel changes!
}

fun main(){

var spaceship = ThrusterSystem()
spaceship.fireThruster(30.023)
// print(spaceship.fuelLevel)
print( spaceship.checkFuel().toDouble() )
}

🧪 Lab Exercise

1. Try to Access fuelLevel Outside the Class

fun main() {
val thruster = ThrusterSystem()
thruster.fireThruster(30.0)
println("🧪 Fuel check: ${thruster.checkFuel()}%")

// Uncommenting the next line will produce an error:
// println(thruster.fuelLevel) ❌ Not allowed!

// No sneaky changes either:
// thruster.fuelLevel = 999.0 ❌ Not allowed!
}

✅ Output:

🔥 Thruster fired using 30.0% fuel. Remaining: 70.0%
🧪 Fuel check: 70.0%

❗Why This Matters

Encapsulation:
Keeps your data safe from unexpected changes
Makes your code easier to reason about
Forces changes to go through controlled logic, like validations

💬 Bonus Discussion Prompt:

Ask students:
“What if the diagnostic tool had to use a setFuelLevel() function with built-in validation instead of writing directly to the variable? Would the disaster have happened?”

🏁 Conclusion:

Encapsulation isn’t just a theory. It’s an essential design strategy that saves real-world systems from bugs, corruption, and catastrophic failures.
Just like the Mars probe, your programs will operate far from your reach—so they better be built to protect themselves.

🔚 Final Note: Why Encapsulation—and Discipline—Matters

As future IT professionals, you may write thousands of lines of code across your career—some trivial, some profound. It might feel like the work you're doing is just another class assignment or simple app project.
But here's the truth:
You don’t know where your code might end up.
That utility class you wrote to sort a list might eventually be repurposed in a power grid management system. A simple heartbeat-monitoring routine could wind up inside a hospital's life support controller.
A small backend API you helped test could be integrated into a water purification system in a disaster zone.

Software is fractal—it scales and migrates. What starts as an innocent function might become a part of a mission-critical system, where your name isn’t listed, but your decisions echo.

That’s why we follow principles like encapsulation. Not because it's academic, but because it forces us to design with intention, clarity, and safety.
We hide internal workings, expose what’s needed, and control access—just like you'd lock the door to a control room.
So here’s a creed to carry forward:

Write every line of code as if it could one day support life itself. If you mess up, someone might lose power. If you’re sloppy, someone might lose a limb. If you skip a check, someone might lose their life.

Not every app you build will be on the front lines of safety—but you must build all of them as if they are.
That is the mark of a Tier One developer. That is how you honor your craft.
Now, go build something great—and safe.
image.png
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.