Get startedGet started for free

Hiding Complexity with Encapsulation

1. Hiding Complexity with Encapsulation

Microwaves are fairly complicated objects. I have to confess that

2. Blank

I only have a very rudimentary understanding of how they work. Fortunately, that doesn't stop me being able to use one. That's because regardless of how advanced the technology is inside the microwave, the user interface is pretty simple. In fact, there are only four pieces of functionality. I can change the power level. I can open the door. I can close it again, and of course, I can cook some food.

3. Encapsulation

In object-oriented programming, the term for

4. Encapsulation

separating the implementation of the object from its user interface is called "encapsulation".

5. microwave_oven_factory

The power rating element of the microwave that you saw in the previous exercises was an example of an implementation detail. In R6, all these implementation details are stored in the private element of the class. By contrast, the user interface details are stored in an element named "public". Just like private, the public element is specified as a named list. Its contents are usually functions. Since the microwave has four pieces of functionality, the R6 MicrowaveOven class needs to have four functions in its public element. Here's the existing version with only the power rating. Let's add a function to open the microwave door. To make this function work, you need another private variable to hold the state of the door. Then, you fill in the body of the function to make it do something. The data fields in the private element can be accessed using a prefix of

6. private$

"private" followed by the dollar indexing operator. It is also possible to access other public elements of a class. This time, rather than using the private dollar prefix, you use "self", then a dollar. You'll see this feature in action in the next chapter.

7. Summary

To summarise, encapsulation means separating implementation details from the user interface. For R6 classes, this means storing data fields in the private element of the class, and functions that you want the user to be able to access in the public element. These public functions can access private elements by typing their name prefixed by "private" and a dollar symbol. Likewise, you can access public elements by using a self-dollar prefix.

8. Let's practice!