< Previous | Contents | Next >

Understanding Encapsulation

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 cant; response1 and response2 dont 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. Thats why you use parameters and return valuesto communicate only the informa- tion that needs to be exchanged. Plus, you dont 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. Thats because theyre 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, youre employing abstraction because you dont 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 cant directly access them. That is, you cant 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.

Working with Scopes 161