What do you think about Proxy Objects?

Forgive me, I do not have access to a compiler.

Anyway, what do you think about the idea of 'proxy objects' instead of getters and setters? Take this example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class A
{
    int vel; //velocity
public:
    A() : vel(51) {}

    class VelocityProxy
    {
        int &Vel;
        VelocityProxy(int &v) : Vel(v) {}
    public:
        VelocityProxy(const VelocityProxy &vp) : Vel(vp.Vel) {}

        VelocityProxy &operator=(const int &v)
        {
            Vel = v > 100 ? 100 : v;
        }
        VelocityProxy &operator=(const VelocityProxy &vp)
        {
            Vel = vp.Vel;
        }

        operator int()
        {
            return(Vel);
        }

        VelocityProxy &operator*=(const int &v)
        {
            Vel *= v;
            Vel = Vel > 100 ? 100 : Vel;
        }
        //and other operators an int normally has
    };

    VelocityProxy &Velocity()
    {
        return(VelocityProxy(vel));
    }
};

//code by user of your library

A obj; //vel == 51
obj.Velocity() *= 2; //VelocityProxy makes sure 51*2->102 goes to 100 

Do you think this is a good idea to make life easier for the users of your library? (Just the concept?)
Last edited on
It doesn't seem to make it any easier. Just make the data public if you want that to be doable. The only time I can think of that you might want to do that is if you need to do different stuff for operator *= or something on an stored int or something.
You are wasting time. By using a reference now you've got to code the copy constructor and assingment operator.
Also, there is a bigger problem here:
1
2
3
 VelocityProxy &Velocity()
    {
        return(VelocityProxy(vel)); //error: non-const reference from an rvalue 
Easy fix VelocityProxy Velocity(); //return an object

I don't see an advantage from making it an inner class either.

Still you could simply do
1
2
3
struct A{
  velocity_clamp vel;
};


¿What about Demeter's Law and Tell, don't ask instead of getters/setters?

Edit:
The only advantage that I see is if you want to do different kind of things to the variable
By instance, now you are making a clamping and later you may want to wrap it.
It seems a little like the 'strategy pattern'.

By the way http://www.cplusplus.com/forum/articles/36872/#msg200792 ¿what are you thoughts on that?
Last edited on
Topic archived. No new replies allowed.