How To Use Decomposition to Solve Problems In iOS
Sep 13, 2024When you think about a rocket as a whole its hard to imagine how to works. It might even seem mysterious that it’s able to take off and break through Earth’s gravity on its way to space. But a rocket is really just a collection of parts. To understand a rocket, you’d have to break it down into smaller pieces.
Decomposition is about breaking down things into smaller pieces to better understand them. Often times, things appear complex when looking at them as a whole but it’s easier to learn how something works when we look at the pieces they are made of. A rocket for example is made up of 4 important pieces. These are the fuel system, the engine, the guidance system and the oxidiser.
Let’s suppose we have a problem with our rocket. The rocket is able to launch but it goes off course. It’s almost obvious we should focus our attention on the guidance system but that’s only because we understand the components of a rocket. The guidance system itself is made up of individual parts so it would seem intuitive to focus our attention on the parts that make up the guidance system. Using this example, you should be able to see you can further break down a system using decomposition to solve a problem.
Let’s look at a practical example. We have the following code that’s responsible for fetching currency exchange rates from an API.
We can decompose this code in a number of ways to make it easier to understand. We will explore a few scenarios.
Decomposition to Understand
If we did not understand what this code does, we could identify the relevant topics we need to know. We can identify them by surveying the code. The following topics will be relevant:
- Async/await
- Error handling with do/catch
- Codable
- Making network requests with URLSession
If I read up on these topics I am better able to understand how the code above works.
Decomposition to Fix Bugs
There’s a problem with our code. When we attempt to make a request to the API we get back a 401 meaning we have made a bad request. Let’s break down the important parts of our code using comments.
If you examine the code, two places in our code throw an error if something is wrong and both are marked with try. There’s either a problem with the actual request we make to the server or a problem with how we decode the JSON. An understanding of the problem is important here. Since our problem is with a bad request we can eliminate anything to do with decoding. The problem is with how we make our request. A request relies on a URL and if we examine the URL on its own you might realise we are missing an API key.
In conclusion, decomposition is a powerful tool to use when trying to understand or solve problems in iOS. By breaking down complex problems into smaller pieces we make it easier to understand how code works.