...

/

Avoiding Conflicts Using Namespaces

Avoiding Conflicts Using Namespaces

Learn about the purpose of namespaces and how to use them.

Namespaces

Previously, we learned how to download a package, but soon we’ll be dealing with another problem. We must make sure that all the names are unique when naming things in our code. If not, the program won’t run. This can be tricky, especially when using packages that others have written. How do we know that the names we’re using are not already being used? The solution is in namespaces.

When writing code, we constantly need to name things. The problem is, what if we give something a name that’s already being used? We now know that the code for an application can consist of thousands of lines of code divided into hundreds of files. How can we ensure that the names we choose for something are not already in use? We also learned that we can install packages with code that others have written. How can we make sure that they haven’t given their packages names that we’ve already used? Or how can we make sure that a package we install is not using names that another package we’ve already installed is using?

Handling names can be tricky. Let’s take a look at an example. Later on in this course, we’ll discuss what a function is and how it works. For this example, all we need to know about functions is that they have a name and consist of several lines of code. We use the function name to call it, which will make the code inside it run.

Example: calculator application

In this example, we’re constructing a calculator app. First, let’s take a look at what the application might look like:

Press + to interact
Calculator application
Calculator application

When the user clicks on the square root button, we have to calculate the square root of the number currently on the display. This means that we need to connect some code with the event that occurs when this button is clicked. This code needs to perform the following steps:

  1. It needs to get the value currently on the display.
  2. Then, it needs to calculate the square root of that value.
  3. Finally, it needs to put
...