Member-only story
How to Write Decoupled Code in Swift
Loosely coupled code is testable code

In this article, I will discuss how to write decoupled code more practically. The examples will be in Swift but they apply to all other languages. This article is a continuation of my previous article, Why Write Unit Tests, where I discussed the importance of writing unit tests.
Let’s start off with what decoupled code is, and why it is important in general and more so when writing unit tests. To understand what decoupled code is, let’s talk about coupled code first.
Coupled code is where a class’ dependencies can’t be changed, meaning the dependencies are hardcoded and use a specific implementation. Let’s take a look at an example
NaughtyClass
creates an instance of sessionManager
, and when btnLogoutTapped
is called, logout is called on the sessionManager
object.
This may seem fine at first and all functionalities will work, however, this code is tightly coupled. Try to think about why NaughtyClass
is in fact naughty, I’ll wait…
SessionManager
is a dependency that can not be replaced, meaning that the logout implementation can’t be changed at runtime. This isn’t a good design in general because what if, in the future, we have a few different kinds of logouts, for example Facebook logout, Google logout, etc.
We won’t be able to easily add those cases, we will need to change the main logout method which will decide which logout to use. This change will affect NaughtyClass
directly and may introduce a bug.
This is also bad for unit tests because we won’t be able to mock SessionManager
. Mocking is a way to create a fake object that can replace SessionManager
to have full control over all of NaughtyClass
dependencies.
This is crucial for unit tests because we need to isolate the class being tested from all its dependencies.
In our example, it is not so hard to realize that our code is tightly coupled, however, in…