Skip to Content
Course content

133: Companion Object Factory Patterns

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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 DbConnection primary constructor private.
  • Create a companion object containing three factory methods: createReadOnlyConnection(url: String), createReadWriteConnection(url: String, apiKey: String), and createAdminConnection(url: String, adminToken: String).
  • In the createAdminConnection method, add a require block to ensure the adminToken starts with the prefix "SECURE_"; otherwise, throw an IllegalArgumentException.
  • Ensure the DbConnection class has properties to store the url, apiKey (nullable), and adminToken (nullable).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.