From 0e676670105200fed25c7e3449f1dfaa6b03280c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sven=20Bergstr=C3=B6m?= Date: Tue, 17 Sep 2019 22:18:55 -0700 Subject: [PATCH] Update Encapsulation documentation to be clearer fixes #691 --- doc/site/classes.markdown | 39 ++++++++++++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 5 deletions(-) diff --git a/doc/site/classes.markdown b/doc/site/classes.markdown index 36d0b4cf..c53444a3 100644 --- a/doc/site/classes.markdown +++ b/doc/site/classes.markdown @@ -369,11 +369,10 @@ value is `null`. ### Encapsulation All fields are *private* in Wren—an object's fields can only be directly -accessed from within methods defined on the object's class. You cannot even -access fields on another instance of your own class, unlike C++ and Java. +accessed from within methods defined on the object's class. -If you want to make a property of an object visible, you need to define a -getter to expose it: +In short, if you want to make a property of an object visible, **you need to define a +getter to expose it**: :::wren class Rectangle { @@ -383,7 +382,7 @@ getter to expose it: // ... } -To allow outside code to modify the field, you'll also need to provide setters: +To allow outside code to modify the field, **you need to provide setters to provide access**: :::wren class Rectangle { @@ -391,6 +390,36 @@ To allow outside code to modify the field, you'll also need to provide setters: height=(value) { _height = value } } +This might be different from what you're used to, so here are two important facts: + +- You can't access fields on another instance of your own class (unlike C++ and Java). +- You can't access fields from a base class. + +Here is an example in code: + + :::wren + class Shape { + construct new() { + _shape = "none" + } + } + + class Rectangle is Shape { + construct new() { + //This will print null! _shape from the parent class is private, + //so we are really just reading `_shape` from `this`, which has not been set. + System.print("I am a %(_shape)") + + //a local variable, all variables are private + _width = 10 + var other = Rectangle.new() + //other._width is not accessible from here, + //even though we are also a rectangle. The field + //is private, and other._width is invalid syntax! + } + } + ... + One thing we've learned in the past forty years of software engineering is that encapsulating state tends to make code easier to maintain, so Wren defaults to keeping your object's state pretty tightly bundled up. Don't feel that you have