Control the Power
Active bindings can also be used to set private fields. In this case, the binding function should accept a single argument, named "value".
The pattern for creating a read/write active binding is as follows.
thing_factory <- R6Class(
"Thing",
private = list(
..a_field = "a value"
),
active = list(
a_field = function(value) {
if(missing(value)) {
private$..a_field
} else {
assert_is_a_string(value) # or another assertion
private$..a_field <- value
}
}
)
)
Values are assigned as though the binding was a data variable, not a function.
a_thing <- thing_factory$new()
a_thing$a_field <- "a new value" # not a_thing$a_field("a new value")
This exercise is part of the course
Object-Oriented Programming with S3 and R6 in R
Exercise instructions
A microwave oven class has been partially defined for you.
- Extend the definition of the microwave oven class to include an
active
list element. - Add an active binding to the
active
element control the power level.- The function should be called
power_level_watts
. - It should accept a single argument named
value
. - The private variable to get/set is called
..power_level_watts
. - Use
assert_is_a_number()
(docs) to check thatvalue
is a single number. - Use
assert_all_are_in_closed_range()
(docs) to check thatvalue
is between0
and..power_rating_watts
.
- The function should be called
- Create a microwave oven object, and assign it to
a_microwave_oven
. - Get the power level.
- Try to set the the power level to the value
"400"
, as a string. - Try to set the power level to
1600
. - Set the power level to
400
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Add a binding for power rating
microwave_oven_factory <- R6Class(
"MicrowaveOven",
private = list(
..power_rating_watts = 800,
..power_level_watts = 800
),
# Add active list containing an active binding
___ = ___(
___ = ___(___) {
if(missing(___)) {
# Return the private value
___
} else {
# Assert that value is a number
___
# Assert that value is in a closed range from 0 to power rating
___
# Set the private power level to value
___ <- ___
}
}
)
)
# Make a microwave
a_microwave_oven <- ___
# Get the power level
___
# Try to set the power level to "400"
___ <- ___
# Try to set the power level to 1600 watts
___ <- ___
# Set the power level to 400 watts
___ <- ___