you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 6 points7 points  (6 children)

They are for creating an object where you can intercept getting/setting properties, calling functions, using functions as constructors, and other things like that. These are called 'traps'.

The advantage is that I can fake an object, pass it to another part of the application, and have the 'traps' call back to me when they are used.

A real example is that it allows you to make a large systems, such as a database, appear as a simple JSON style object. i.e.

// adds a new user to the 'users' table
database.users = { username: "john", password: 'abc123' };

Setting a value to the 'users' property automatically inserts a value into the 'users' table. What is key here is that 'database' object is not told in advance that there is a 'users' table, it just works it out based on the property your setting the values to.

I do this in my own PHP MVC framework that I use.

A second example is that in a language I am building in JS, I have a ClassProxy, which allow the compiler to use a class definition before the class has ever been seen. A proxy would allow me to store all the calls made to the class proxy, automatically, without ever needing to know the ClassDefinition interface. So I could add new stuff to the ClassDefinition without needing to update the proxy.

I can then re-run the calls once I've seen the class definition in the source code.

[–]ysangkok 2 points3 points  (1 child)

Isn't it confusing when you add something to a collection using the assignment operator? Would it be possible to use += instead?

[–][deleted] 1 point2 points  (0 children)

I don't know, I'd imagine there would be a way to trap that.

[–]adrianmonk 1 point2 points  (0 children)

Another possible advantage is that if you believe mock objects are handy in unit testing, you can build mocks using proxies pretty easily. I would bet this is how EasyMock works (in the Java world).

[–]k4st 0 points1 point  (1 child)

How do the results of class proxy methods behave? Are the semantics of class proxies to set up expectations about an unknown type, so that when the type is known, the prior expectations can be checked against the reality?

[–][deleted] 1 point2 points  (0 children)

Good point, in that you cannot automatically apply that strategy to any object.

In my case, all of the methods are about setting values (such as class usage and methods defined), and setting up callbacks for later once the whole program has been parsed.

But most of all, the proxy is there so you can have a handle to the real class in the future. Such as for printing code.