oop-examples/lessons/Properties.md

62 lines
1.8 KiB
Markdown
Raw Permalink Normal View History

2020-05-24 19:13:09 +02:00
# Properties
Properties are a way to restrict read/write access to a field and to add
additional verifications, computations or function calls to accessing a field.
To define a property you need one private field that stores your data and the
getter/setter for it. If you don't want it to be readable or writable, you can
leave out either of the accessor functions.
None of the languages featured here have a full implementation of properties.
Languages like c# and Delphi do though.
Delphi has the simplest syntax for properties I've seen so far.
```pas
// this property will read from the field FFoo and write using the function set_foo
property Foo read FFoo write set_foo;
```
C# is a bit more complicated, but still better than the languages here
```cs
public string Foo
{
get => _foo;
set {
_foo = do_something(value);
}
}
```
## Typescript
Typescript allows a somewhat property implementation. In the class itself you
define getter and setter functions using the get and set keywords
```ts
public get foo(): string {
return this._foo;
}
public set foo(val: string): void {
this._foo = do_something(val);
}
```
From the outside, the property can be read and written like in c# and Delphi,
just like working with a variable.
## C++, Java and Rust
Those languages don't provide a property syntax at all, instead you have to
create public functions like set_foo and get_foo to replace them.
## Additional note to rust
Properties don't exist in rust either. But replacing them with getters and
setters is also discouraged. Quoting from a reddit post
`Expose behavior, not state`. That means you should present functions to outside
viewers and not your plain data. An object should be able to do all its intended
functions itself without having an outside observer read or write its data.