Builder Pattern with Kotlin

Syed Ovais Akhtar
5 min readAug 7, 2023

--

Complex Object in a simpler way!

In the ever-evolving landscape of software development, mastering design patterns is akin to unlocking a treasure trove of best practices and proven methodologies. Among these gems, the Builder Pattern shines as a beacon of structured object creation, offering a systematic approach to managing complexity while keeping codebases elegant and maintainable.

By journeying through the intricacies of the Builder Pattern, we have unveiled a mechanism that goes beyond mere code organization. We have discovered a tool that empowers us to craft software solutions with precision, enhancing our ability to adapt and iterate as projects evolve. The Builder Pattern’s ability to abstract away the intricacies of object construction not only enhances the readability of our code but also fosters collaboration among development teams, leading to more efficient and cohesive projects.

As you reflect on the insights gained from this exploration, you are equipped with more than just a technical understanding of the Builder Pattern. You possess a valuable perspective that transcends code syntax — a perspective that can guide you in architecting solutions that balance complexity and simplicity.

So, whether you’re a seasoned developer seeking to optimize your codebase or a newcomer eager to grasp foundational design concepts, the Builder Pattern stands as a timeless tool with applications spanning various domains and languages. As you continue to refine your software engineering skills, remember the lessons of the Builder Pattern, and let its principles guide you towards more elegant, maintainable, and robust software designs.

In the world of software design, creating complex objects and structures often requires a meticulous balance between flexibility, readability, and maintainability. As projects grow in complexity, maintaining clear and concise code becomes paramount to prevent development bottlenecks and enhance collaboration among team members. This is where design patterns come into play, offering battle-tested solutions to common software design challenges.

One such design pattern that has gained significant traction is the Builder Pattern. The Builder Pattern provides an elegant and efficient way to construct complex objects step by step, abstracting away the intricate details of object creation while ensuring that the resulting object is properly configured and consistent. Whether you’re a novice programmer or an experienced software architect, understanding and utilizing the Builder Pattern can greatly improve your codebase’s structure, readability, and maintainability.

In this comprehensive guide, we will delve into the fundamental concepts of the Builder Pattern, explore its various components and variations, and provide real-world examples that highlight its benefits. By the end, you’ll not only have a solid grasp of the Builder Pattern’s inner workings but also be equipped to leverage its power in your own software projects.

Join us on this journey to demystify the Builder Pattern and unlock a powerful tool that can elevate your software design to new heights. Whether you’re looking to streamline object creation, enhance code reusability, or improve collaboration within your development team, the insights gained from this guide will undoubtedly prove invaluable in your quest to write clean, maintainable, and efficient code.

Let’s take an example, We are integrating some social platforms in our apps like Facebook or YouTube, and suppose Facebook has only an access token and youtube has both a refresh token and access token.

Let’s take the example of sending tokens to our server or anywhere in the app in which we have some data and some tokens.

data class TokenRequest(
val accessToken: String,
val refreshToken: String?,
val platform: String,
val pageList: List<String>
)

Now we have to put data in the attributes of the class or have to send null or fill out attributes with the named parameters in Kotlin

TokenRequest(
accessToken = "SOME_ACCESS_TOKEN",
refreshToken = null,
platform = "SOME_PLATFORM",
pageList = listOf()
)
TokenRequest(
accessToken = "SOME_ACCESS_TOKEN",
platform = "SOME_PLATFORM"
)

Now let’s deep dive into the correct way!


class TokenRequest private constructor(
val accessToken: String?,
val refreshToken: String?,
val platform: String?,
val pages: ArrayList<String>?
) {

class Builder() {
private var accessToken: String? = null
private var refreshToken: String? = null
private var platform: String? = null
private var pages: ArrayList<String>? = null

fun setAccessToken(token: String): Builder {
this.accessToken = token
return this
}

fun setRefreshToken(token: String): Builder {
this.refreshToken = token
return this
}

fun setPlatform(platform: String): Builder {
this.platform = platform
return this
}

fun setPage(page: String): Builder {
this.pages?.add(page)
return this
}

fun setPages(pages: List<String>): Builder {
this.pages?.addAll(pages)
return this
}

fun build(): TokenRequest {
return TokenRequest(
accessToken,
refreshToken,
platform,
pages
)
}
}
}

Now we can easily add what we want!

 TokenRequest
.Builder()
.setAccessToken("SOME_ACCESS_TOKEN")
.setRefreshToken("SOME_REFRESH_TOKEN")
.setPage("PAGE_O1")
.setPages(listOf("PAGE_02","PAGE_03","PAGE_04"))
.build()

In the ever-evolving landscape of software development, mastering design patterns is akin to unlocking a treasure trove of best practices and proven methodologies. Among these gems, the Builder Pattern shines as a beacon of structured object creation, offering a systematic approach to managing complexity while keeping codebases elegant and maintainable.

By journeying through the intricacies of the Builder Pattern, we have unveiled a mechanism that goes beyond mere code organization. We have discovered a tool that empowers us to craft software solutions with precision, enhancing our ability to adapt and iterate as projects evolve. The Builder Pattern’s ability to abstract away the intricacies of object construction not only enhances the readability of our code but also fosters collaboration among development teams, leading to more efficient and cohesive projects.

As you reflect on the insights gained from this exploration, you are equipped with more than just a technical understanding of the Builder Pattern. You possess a valuable perspective that transcends code syntax — a perspective that can guide you in architecting solutions that balance complexity and simplicity.

So, whether you’re a seasoned developer seeking to optimize your codebase or a newcomer eager to grasp foundational design concepts, the Builder Pattern stands as a timeless tool with applications spanning various domains and languages. As you continue to refine your software engineering skills, remember the lessons of the Builder Pattern, and let its principles guide you towards more elegant, maintainable, and robust software designs.

--

--

Syed Ovais Akhtar
Syed Ovais Akhtar

Written by Syed Ovais Akhtar

Senior Software Engineer - Mobile

No responses yet