This article compares four approaches to handling dependencies in Object-Oriented Programming: constructor injection, parameter passing, ThreadLocal, and Kotlin’s new context parameters. Each technique is analyzed for testability, coupling, and readability. While constructor injection remains the standard, Kotlin’s evolving language features, particularly context parameters, introduce an elegant, implicit alternative for dependency management in modern OOP design.This article compares four approaches to handling dependencies in Object-Oriented Programming: constructor injection, parameter passing, ThreadLocal, and Kotlin’s new context parameters. Each technique is analyzed for testability, coupling, and readability. While constructor injection remains the standard, Kotlin’s evolving language features, particularly context parameters, introduce an elegant, implicit alternative for dependency management in modern OOP design.

Understanding Dependency Injection in Object-Oriented Programming

In Object-Oriented Programming, objects collaborate. The initial idea of collaboration, first found in Smalltalk, was for object A to send a message to object B. Languages designed later use method calling. In both cases, the same question stands: how does an object reference other objects to reach the desired results?

In this post, I tackle the problem of passing dependencies to an object. I will go through several options and analyze their respective pros and cons.

Constructor injection

For constructor injection, you pass dependencies as parameters to the constructor.

class Delivery(private val addressService: AddressService,                private val geoService: GeoService,                private val zoneId: ZoneId) {      fun computeDeliveryTime(user: User, warehouseLocation: Location): ZonedDateTime {         val address = addressService.getAddressOf(user)         val coordinates = geoService.getCoordinates(location)         // return date time     } } 

Constructor injection is by far the most widespread way to pass to an object its dependencies: for about ten years, every codebase I've seen has constructor injection.

I've a slight issue with constructor injection: it stores dependencies as fields, just like state. Looking at the constructor's signature, it's impossible to distinguish between the state and dependencies without proper typing.

It bugs me. Let's see other ways.

Parameter passing

Instead of storing the dependencies along with the state, we can pass the dependency when calling the method.

class Delivery(private val zoneId: ZoneId) {      fun computeDeliveryTime(addressService: AddressService,                             geoService: GeoService,                             user: User, warehouseLocation: Location): ZonedDateTime {         val address = addressService.getAddressOf(user)         val coordinates = geoService.getCoordinates(location)         // return date time     } } 

The separation of state and dependencies is now clear: the former is stored in fields, while the latter is passed as function parameters. However, the responsibility of handling the dependency is moved one level up the call chain. The longer the call chain, the more unwieldy it gets.

class Order() {      fun deliver(delivery: Delivery, user: User, warehouseLocation: Location): OrderDetails {         // Somehow get the address and the geo services         val deliveryTime = delivery.computeDeliveryTime(addressService, geoService, user, warehouseLocation)         // return order details     } } 

Note that the call chain length is also a problem with constructor injection. You need to design the code for the call site to be as close as possible to the dependency creation one.

ThreadLocal

Legacy design makes use of the ThreadLocal:

\

\ We can rewrite the above code using ThreadLocal:

class Delivery(private val zoneId: ZoneId) {      fun computeDeliveryTime(user: User, warehouseLocation: Location): ZonedDateTime {         val addressService = AddressService.get()         val geoService = GeoService.get()         // return date time     } } 

\ The ThreadLocal can be either set up in the call chain or lazily, on first access. Regardless, the biggest disadvantage of this approach is that it completely hides the dependency. There's no way to understand the coupling by only looking at the class constructor or the function signature; one needs to read the function's source code.

Additionally, the implementation could be a regular singleton pattern, with the same downsides.

Kotlin context

The last approach is Kotlin-specific and has just been promoted from experimental to beta in Kotlin 2.2.

Here's how we can migrate the above code to context parameters:

class Delivery(private val zoneId: ZoneId) {      context(addressService: AddressService, geoService: GeoService)     fun computeDeliveryTime(user: User, warehouseLocation: Location): ZonedDateTime {         // return date time     } } 

And here's how to call it:

context(addressService,geoService) {     delivery.computeDeliveryTime(user, location) } 

Note that the call can be nested at any level inside the context.

Summary

| Approach | Pros | Cons | |----|----|----| | Constructor injection | Testable | Mix state and dependencies | | Parameter passing | Testable | Noisy | | ThreadLocal | | Hides coupling | | Context parameter | Get dependencies on deeply-nested | Limited to Kotlin |

I guess I'll continue to use constructor injection, unless I'm coding in Kotlin. In this case, I'll be happy to use context parameters, even though they are in beta.


Originally published at A Java Geek on October 12th, 2025

Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council

Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council

The post Best Crypto to Buy as Saylor & Crypto Execs Meet in US Treasury Council appeared on BitcoinEthereumNews.com. Michael Saylor and a group of crypto executives met in Washington, D.C. yesterday to push for the Strategic Bitcoin Reserve Bill (the BITCOIN Act), which would see the U.S. acquire up to 1M $BTC over five years. With Bitcoin being positioned yet again as a cornerstone of national monetary policy, many investors are turning their eyes to projects that lean into this narrative – altcoins, meme coins, and presales that could ride on the same wave. Read on for three of the best crypto projects that seem especially well‐suited to benefit from this macro shift:  Bitcoin Hyper, Best Wallet Token, and Remittix. These projects stand out for having a strong use case and high adoption potential, especially given the push for a U.S. Bitcoin reserve.   Why the Bitcoin Reserve Bill Matters for Crypto Markets The strategic Bitcoin Reserve Bill could mark a turning point for the U.S. approach to digital assets. The proposal would see America build a long-term Bitcoin reserve by acquiring up to one million $BTC over five years. To make this happen, lawmakers are exploring creative funding methods such as revaluing old gold certificates. The plan also leans on confiscated Bitcoin already held by the government, worth an estimated $15–20B. This isn’t just a headline for policy wonks. It signals that Bitcoin is moving from the margins into the core of financial strategy. Industry figures like Michael Saylor, Senator Cynthia Lummis, and Marathon Digital’s Fred Thiel are all backing the bill. They see Bitcoin not just as an investment, but as a hedge against systemic risks. For the wider crypto market, this opens the door for projects tied to Bitcoin and the infrastructure that supports it. 1. Bitcoin Hyper ($HYPER) – Turning Bitcoin Into More Than Just Digital Gold The U.S. may soon treat Bitcoin as…
Share
BitcoinEthereumNews2025/09/18 00:27
Trump's border chief insists Americans support ICE – and is shut down by host: 'Come on!'

Trump's border chief insists Americans support ICE – and is shut down by host: 'Come on!'

Border Patrol Chief Greg Bovino was shut down Friday during an appearance on NewsNation after suggesting that federal immigration officials enjoyed widespread support
Share
Rawstory2026/01/23 22:36
The Economics of Self-Isolation: A Game-Theoretic Analysis of Contagion in a Free Economy

The Economics of Self-Isolation: A Game-Theoretic Analysis of Contagion in a Free Economy

Exploring how the costs of a pandemic can lead to a self-enforcing lockdown in a networked economy, analyzing the resulting changes in network structure and the existence of stable equilibria.
Share
Hackernoon2025/09/17 23:00