Chuck wrote:Sometimes I would like to ensure that an object variable is not accessed other than through its corresponding property. In other words, I don't want methods(*) to access the variable, except through that property. Here is the idea:
class Example
pro name as String
var _name # <-- var decl *inside* a property. type is assumed to match the property
get
return _name
set
_name = value.trim
def foo
_name = 'foo' # error: Variable _name is enclosed by property; use .name instead.
(*) or other code members such as properties and indexers
Reactions?
This is a fantastic idea, let's have it. My only concern is that the inner variable name remains preceded by an underscore, when it is clearly not protected in the sense that regular object variables are protected. I guess can live with that, provided that we grant derived classes that override the property access to the inner variable. E.g.:
class Foo
pro bar as int
var _bar = 0
get
return _bar
set
_bar = value
class Derived
pro bar as int is override
get
return _bar * 2 # has access
set
_bar = value / 2 # ditto
Of course, Derived would not have access to the inner var had it been defined with two leading underscores (i.e., private). I guess you had already thought about that, but I just wanted to make sure.
You suggest that we will be allowed to define several inner variables for each property, each with its own type. If that is the case, then I suggest that we force the inner variable's type to be specified even when it coincides with that of the property. E.g., in your initial example, we would be forced to write "var _name as String" instead of simply "var _name". The reason is that to me it would be ugly to see something like:
class Foo
pro name as String
var _x as int
var _foo # as what?? it's not so obvious that it should be String if it's no longer named as the property
get
return _foo * _x
set
_foo = value / _x
If we really want to avoid typing the type of the property twice, then I suggest a more readable syntax shortcut
class Foo
pro bar as int
var _bar as pro # int
get
return _bar
set
_bar = value
Chuck wrote:class Example
var _foo as String
has VisibleTo('foo', 'bar')
I would vote against this, IMHO it looks like a needless complication, and it will make code less readable. I would hate to have to read code written by someone else that makes heavy use of this feature.