Low coupling

Coupling is the measure of code dependency. We always want to reduce coupling and make our code components as independent of each other as possible. Low coupling allows us to change a component without affecting other code components. Low-coupled code is easier to read because each component has its own relatively small area of responsibility, though we need to understand only this code without spending time on figuring out how the entire system works.

Immutability helps in achieving low coupling. Immutable data can be safely passed through different code blocks without worrying about it being transformed and affecting other parts of the code. Pure functions transform the data and return the result without affecting the input data. So, if the function contains errors, we can easily find it. Also, using value types and immutable data structures means that we can significantly reduce object referencing.

The following shows the data transformation idea. We have immutable array numbers, and we need the sum of all the even numbers that it contains:

let numbers: [Int] = [1, 2, 3, 4, 5] 
let sumOfEvens = numbers.reduce(0) {
$0 + (($1 % 2 == 0) ? $1 : 0)
}

The numbers array is not changed and can be passed to any other function without any side-effects:

print(numbers) // [1, 2, 3, 4, 5] 
print(sumOfEvens) // 6

Using in-place transformation of the immutable data will help us reduce coupling.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset