On Sunday, 12 March 2017 at 10:47:35 UTC, Andrey wrote:
Hello, how better to declare properties, for example I have
class:
class Foo {
this(in int x, in int y, Bar bar) {
this.x = x;
this.y = y;
this.bar = bar;
}
private:
int x;
int y;
Bar bar;
}
And I want make access to read x, y and bar. Probably I should
add prefix for private members, that is a question: what prefix
should I use? Now I use prefix p_ (from the word property), but
maybe prefix m_ is better and you need to use it for all
private members?
Another question: what style is better for declare getters?
this:
class Foo {
@property int x() { return p_x; // or m_x; }
@property int y() { return p_y; // or m_y; }
@property int bar() { return p_bar; // or m_bar; }
}
or this:
class Foo {
@property {
int x() { return p_x; }
int y() { return p_y; }
int bar() { return p_bar; }
}
}
And one more question: should I add ref for property, to be
able do this (if setter is declared):
foo.x += 5
You should only declare getters/setters if you need to (or think
you may need to later)
intercept the assignment or acquisition of a variable
(logging, computing on demand)
have a field as externally read only (setter only)
otherwise you should have the variables as normally assignable.
A single leading underscore is usually used to denote a private
variable ( names prefixed with two leading underscores are
reserved for use by the compiler).
If you must use @property and you have a whole lot of them in a
row the second form is preferred (consider also using
`@property:` if you have no more non-@property function to
declare). Note that you still need to declare the variables you
are going to return in the property
if the variable you are going to return is ref then unless you
are choosing which variable to return at runtime (see first
paragraph) then just have the variable be public.