Thread overview
Readonly-to-outside variable
Apr 28, 2015
tcak
Apr 28, 2015
Justin Whear
Apr 28, 2015
Baz
April 28, 2015
Is there any way to define a variable or an attribute as read-only without defining a getter function/method for it?

Thoughts behind this question are:
1. For every reading, another function call process for CPU while it could directly read the value from memory.

2. Repetition of same name for variable and getVariableName. (Some might not agree with this but I like the code when it looks nice.)

April 28, 2015
On Tue, 28 Apr 2015 19:30:04 +0000, tcak wrote:

> Is there any way to define a variable or an attribute as read-only without defining a getter function/method for it?
> 
> Thoughts behind this question are:
> 1. For every reading, another function call process for CPU while it
> could directly read the value from memory.
> 
> 2. Repetition of same name for variable and getVariableName. (Some might not agree with this but I like the code when it looks nice.)

1. I wouldn't worry too much about the performance--compiling with gdc or
ldc with inlining should reduce it to a simple access.
2. You can clean it up if it annoys you with something like this:

mixin template readonly(T, string name)
{
    mixin(`private T _`~name~`;T `~name~`()@property{return _`~name~`;}`);
}

Use it like:

class Foo
{
    // injects a private int _x, public int x()
    mixin readonly!(int, "x");
}
April 28, 2015
On Tuesday, 28 April 2015 at 19:30:06 UTC, tcak wrote:
> Is there any way to define a variable or an attribute as read-only without defining a getter function/method for it?
>
> Thoughts behind this question are:
> 1. For every reading, another function call process for CPU while it could directly read the value from memory.
>
> 2. Repetition of same name for variable and getVariableName. (Some might not agree with this but I like the code when it looks nice.)

an quick attempt:

---
union ReadOnlyOutside(T)
{
    alias value this;
    private T _value;
    public const T value;
}
---

when you declare such a variable inside a struct or a class, the code located in another module won't be able to modify the value:

module1:

---
struct Foo
{
    ReadOnlyOutside!size_t roField;
}
---

module2:

void something(ref Foo foo)
{
    writeln(foo.roField); // OK
    writeln(foo.roField.value); // OK
    foo.roField = 1; // FAIL
    foo.roField.value = 1,// FAIL (because const).
    foo.roField._value = 1,// FAIL (because not visible).
}