On Monday, 12 April 2021 at 18:16:14 UTC, Jack wrote:
Give this class:

```d
class A
{
        int X() { return x; }
        int X(int v) { return x = v;}

        private int x;
}
```

I'd like to allow use ```+=```, ```-=``` operators on ```X()``` and keep encapsulation. What's a somehow elegant way to do that?

I assume you know what you are doing, right?
In this specific case I would say you can probably stick with it as is since you can have value checks in getter/setter, you can validate and correct values before it mess up the internal state, and calculate X without exposing internal state (today it may be int x, tomorrow you change it to be stored as string, who knows...).

But this example doesn't really tell if it's acceptable in what you are trying to achieve.

Otherwise:

What you need is called abstraction, you provide high level interface to your problem without exposing internal state which is implementation detail, which gives you freedom to modify internal logic without breaking everyone's code that consume your interface.

Assuming A is some special scalar type you just implement all operations in a way that makes it only relevant as a whole. Otherwise if you still need to peek on its private members you have leaky abstractions (it is called feature envy).

Reply via email to