Chapter 11. Scope: hiding information
This chapter covers
- The dangers of global variables
- The benefits of local variables
- Using namespaces to reduce global variables
- Creating local variables with functions
- Returning an interface for the user
You want the user to be able to interact with your console-based programs. But you don’t want to give them too much control! This chapter explores ways of hiding parts of your program from the user at the console and clearly defining the properties and methods you expect them to use. For example, for a quiz program the user should be able to submit an answer but not change their score:
By separating the public interface from the private variables and functions that make the program work, you declare your intentions, setting out what a user can do and what other programmers using your code should do, and reduce the risk of code being misused. That’s good for the program, for the players, and for other programmers.