< Previous | Contents | Next >
You might not see the need for return values when you are using your own functions. Why not just use the variables response1 and response2 back in the main()? Because you can’t; response1 and response2 don’t exist outside of the functions in which they were defined. In fact, no variable you create in a function, including its parameters, can be directly accessed outside its function. This is a good thing, and it is called encapsulation. Encapsulation helps keep independent code truly separate by hiding or encapsulating the details. That’s why you use parameters and return values—to communicate only the informa- tion that needs to be exchanged. Plus, you don’t have to keep track of variables you create within a function in the rest of your program. As your programs get large, this is a great benefit.
Encapsulation might sound a lot like abstraction. That’s because they’re closely related. Encapsulation is a principal of abstraction. Abstraction saves you from worrying about the details, while encapsulation hides the details from you. As an example, consider a television remote control with volume up and down buttons. When you use a TV remote to change the volume, you’re employing abstraction because you don’t need to know what happens inside the TV for it to work. Now suppose the TV remote has 10 volume levels. You can get to them all through the remote, but you can’t directly access them. That is, you can’t get a specific volume number directly. You can only press the up volume and down volume buttons to eventually get to the level you want. The actual volume number is encapsulated and not directly available to you.