Black Box Programming in iOS
Aug 21, 2024Imagine a big black box. You do not know what's inside and there's no way to open it. What you do know is that if you touch the box it emits a low vibrational hum. There's no way of telling how it makes that sound. You might speculate there's some kind of speaker inside but there's no way to be sure. Now suppose if you touch the black box a certain way you could almost play it like an instrument. If you push it hard it emits a low bass like sound. If you touch it lightly it makes a high pitch sound. This example illustrates how black box programming works.
Black box programming is a computer science concept. It's a useful concept in iOS in writing and studying code. The idea of black box programming is that how something works is not always very important. As long as you know how to interact with a system and you can reliably predict what kind of outputs you get that's all that matters.
Many things in Swift can be viewed as a black box. Let's look at the example of a function. There are many functions we use in Swift we do not even question. For example, we have the function setImage(_:) which is used in UIKit to set images on buttons. We know the expected input. We have to set some kind of UIImage into setImage(_:). We know the expected output. We see some kind image on the button. But no point are we worried about the actual code behind the function that drives this. Therefore, the function is a black box. We do not see the code behind the function but we know how to use the function.
The concept of the black box can be extended to classes, structs and even libraries. All of these hide the implementation details but present ways of interacting with them for some kind of output. If you think about it, this makes our lives easier. We do not have to question how the thousands of pre-made functions and classes Swift gives us really work inside. We just have to know how to use them.
When you study how to code, the concept of black box programming is useful because it narrows your focus to simply understanding how and not what. You do not always need to know what is inside a function or a class. You simply need to know how to use them and often times this comes with practice. The concept also helps with how we write our code. We should aim to build modular code that people can presents clear inputs and reliable outputs. Users of our code should not have to worry about the implementation details of the modules we create.