Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
133: Companion Object Factory Patterns
You've probably seen classes with constructors that look like a shopping list of optional parameters. At first, it feels flexible. You think, "I'll just make everything nullable or provide defaults, and the caller can decide what they need." But as soon as that class hits a real production environment, you realize you've just handed the keys to the kingdom to every other developer on the team, and they're starting to create objects in states that should be physically impossible.
The "Everything is Optional" Trap
Let's look at a common scenario: an Order system. In a naive implementation, you might try to handle different types of orders—like a Guest checkout versus a Registered Member checkout—within a single public constructor. It usually looks something like this:
class Order(
val orderId: String,
val items: List<Item>,
val userId: String? = null,
val guestEmail: String? = null
)
On the surface, it works. But look at the cost. I can now instantiate an Order that has neither a userId nor a guestEmail. Or, even worse, I can create one that has both, which makes no sense in our business logic. Every time I use this Order object elsewhere in the code, I'm forced to write cumbersome if (userId != null) checks or use the !! operator because the compiler can't guarantee which state the object is actually in. We've traded a little bit of convenience at the call site for a lifetime of null-pointer anxiety.
Hiding the Machinery with Companion Objects
The better way to handle this is to take the constructor away from the public. By making the constructor private, you stop the "wild west" instantiation. You then use a companion object to provide explicit, named factory methods. This isn't just about organizing code; it's about creating a contract.
class Order private constructor(
val orderId: String,
val items: List<Item>,
val userId: String?,
val guestEmail: String?
) {
companion object {
fun createGuestOrder(orderId: String, items: List<Item>, email: String): Order {
require(email.contains("@")) { "Valid email is required for guest orders" }
return Order(orderId, items, null, email)
}
fun createMemberOrder(orderId: String, items: List<Item>, userId: String): Order {
require(userId.isNotBlank()) { "User ID cannot be blank for member orders" }
return Order(orderId, items, userId, null)
}
}
}
Now, when you're typing Order. in your IDE, you aren't staring at a confusing list of parameters. You're presented with two clear choices: createGuestOrder or createMemberOrder. I love this approach because it allows us to bake validation directly into the creation process. If a guest order requires a valid email, we check it before the object is even born. We've moved the failure point from "somewhere deep in the business logic" to "the exact moment of instantiation."
Where This Actually Wins
You might ask why we don't just use a separate Factory class. In many languages, that's the standard. But in Kotlin, the companion object is the idiomatic choice because it keeps the factory logic physically attached to the class it's creating. It signals to anyone reading the code: "This is the only way to get an instance of this class."
The trade-off here is a slight increase in verbosity—you have to write a few more lines of code to define the factory methods. But in my experience, that's a bargain. You're replacing ambiguous constructors with a domain-specific language. Instead of guessing what null means in the third parameter of a constructor, your colleague sees createMemberOrder and knows exactly what the intent is. It turns your code from a set of instructions into a set of rules.
📋 Practical Task
Implementing a Secure Connection Factory
You are building a database wrapper. You need a DbConnection class that can be initialized in three distinct modes: READ_ONLY, READ_WRITE, and ADMIN.
To prevent developers from accidentally creating an ADMIN connection without a secure token, or a READ_ONLY connection with write-permissions, implement the following:
- Make the
DbConnectionprimary constructorprivate. - Create a
companion objectcontaining three factory methods:createReadOnlyConnection(url: String),createReadWriteConnection(url: String, apiKey: String), andcreateAdminConnection(url: String, adminToken: String). - In the
createAdminConnectionmethod, add arequireblock to ensure theadminTokenstarts with the prefix"SECURE_"; otherwise, throw anIllegalArgumentException. - Ensure the
DbConnectionclass has properties to store theurl,apiKey(nullable), andadminToken(nullable).
There are no comments for now.