[rust-dev] Getter and setters

Masklinn masklinn at masklinn.net
Sun Jul 22 11:31:48 PDT 2012


On 2012-07-22, at 20:18 , Patrick Walton wrote:
>> That said personally I think there is no point having properties and
>> prop functions unless  you can have "private"  fields which im not sure
>> Rust can do as you need a "this" pointer which then makes you an OO
>> language .
> 
> Classes (now structs) do have private fields. Methods have an implicit (soon to be explicit) "this" pointer.
> 

But do they have public fields, and if so why? That is what "properties"
try to solve on two fronts: 

* public fields often can't be part of abstract types (e.g. interfaces)
where methods can, in statically typed languages (or at least in C#) so
can properties.
* public fields and methods are not compatible, syntactically or
binary-ly. In languages with public fields and methods, this often leads
to syntactically noisy defensive code "just in case" (see: java's or
C++'s getter/setter disease — where IDEs even have support for
generating these monsters) a field ever needs to be replaced by a less
straightforward access handling. C# also has the issue with its
properties (properties and fields are not compatible at the
binary/bytecode level) but "autogenerated" properties provide a rather
terse way to declare a "public" field. In dynamically typed languages
(e.g. Python), properties can be added post-facto to replace a field by
a computation (they are drop-in compatible in everything but reflective
access)

There is also the option of not allowing public fields at all, which
solves the issue of transitioning a public field to private/computed,
which is what e.g. Smalltalk used to do. Ruby does the same although
they have added some sugar (method names ending with `=` will behave as
writable attributes, and Object also has three methods autogenerating
accessor methods: attr_writer, attr_reader and attr_accessor).

Now as I noted above, I do not know if Rust has public fields. If it
does, I think that's a mistake especially if the compiler is smart
enough to inline "accessor methods", but in that case the discussion
needs to happen now, it *will* be held against the language down the
line.


More information about the Rust-dev mailing list