George B. answered 05/04/19
Senior iOS Developer
Loose coupling is basically the idea that different components of you project should be somewhat independent of one another. Meaning that each separate component should work on their own and not necessarily require or rely on other components to work. By making your code loosely coupled, a change in one component is not likely to inadvertently break another area.
Imagine you want to build a function that will return a description of the current data and time. A very naive and 'tightly coupled' way of doing that would be like this (using pseudocode):
function currentDate() -> String {
timezone = EST
format = 'm-d-y H:m:s'
return Now(withTimezone: timezone).stringWithFormat(format)
}
This works great for users in the eastern timezone. But if you move from the east coast to the west coast, this function breaks and no longer returns the expected result. To make this more loosely coupled, we should pass the users timezone into the function as a parameter. This way, the function is 'decoupled' or 'loosely coupled' from the users location. The users timezone is determined elsewhere. Our function does not need to know anything about how the timezone is determined. It will just return the result based on whatever timezone it gets passed. Here is a the more loosely coupled function:
function currentDate(forTimezone: timezone) -> String {
format = 'm-d-y H:m:s'
return Now(withTimezone: timezone).stringWithFormat(format)
}
We can take this a step further an even further 'decouple' this function from the user. What if you want to change how the date if formatted? Instead of created 10 different functions to return different formats, why not pass the format we want into out function, like this:
function currentDate(forTimezone: timezone, withFormat format) -> String {
return Now(withTimezone: timezone).stringWithFormat(format)
}
Now our function can stand by itself and other components changing, like the users location or the format we want, will not break the function. In this case we have 'decoupled' the users location and desired date format from our function.
Hopefully this helps. Let me know if you have any questions.