Chapter 10 - Encapsulation and Embedding
Exercise 1: Encapsulation
It shouldn’t be possible, but users of our rectangle type are setting its length and width fields to negative values. We need to encapsulate these fields and add getter and setter methods to control access to them.
Update the rectangle type so that the program below will compile, run, and produce the output shown.
- Move the
rectangletype and all its existing methods to a newshapespackage. - You’ll need to rename the type and its existing methods so they’re exported from the new package.
- Leave the struct fields unexported, however, so they can only be accessed through your getter and setter methods.
- The setter methods should return a single
errorvalue. If any value less than0is passed, return an error value indicating the value is invalid. Otherwise, returnnil.
package main
import (
"fmt"
"log"
"shapes"
)
// check logs an error and exits if the error is not nil.
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
var r shapes.Rectangle
err := r.SetLength(4.2)
check(err)
fmt.Println("Length:", r.Length())
// Set width to an invalid value.
err = r.SetWidth(-2.3)
check(err)
fmt.Println("Width:", r.Width())
}Output:
Length: 4.2
2019/05/31 18:46:50 invalid width: -2.300000
exit status 1
When you’re ready, have a look at our solution.