The Proxy pattern

The proxy pattern is a software design pattern.

It is basically, in its simplest form, an interface to something else.

But let's take a look at what it is and how you could use it!

🧵👇🏻
1⃣ What is it?

A Proxy is a wrapper (object), that wraps another object.

Imagine it like a container that looks exactly like the object it wraps, behaves nearly the same, but may add some additional functionality.

You can imagine it, visually, like shown below.
If you need another example:

Imagine a wetsuit. It's a thin layer above your body, keeps the shape of your body, but adds the ability to keep you dry inside!

👇🏻
2⃣ What is it good for?

Proxying is a great pattern to use when you want to add additional functionality to an object, e.g.!

A very simple use case would be an access level audit log, which fires every time you access or set a property on an object or call a method on it.
Another, more complex use-case, is the usage of proxy objects in object relational mappers (short: ORMs).

You sometimes get proxy objects instead of plain objects when you fetch data.

This enables the frameworks to fetch only some of the data, and add lazy fetch functionality.
Although you might have a user object at hand, which has a relationship to multiple posts, some ORMs would only fetch the user.

As soon as you access a post or a collection of posts, the proxy fires another fetch and only then returns the real nested object!

👇🏻
3⃣ Language-level support in JavaScript

Copying each and every property, and method, and...and...and of an object may seem like way too much work to do manually, and you are right!

This is why many languages, including JavaScript have added meta programming capabilities...
...to their standard libs and runtimes.

The simplest form of a proxy in JavaScript, one that simply forwards everything to the original object, without adding any functionality, can be seen below.

The second argument here is an empty handler object.
If you want to recreate the audit logging as a Proxy, you can see a very simplified version of how you could do it below.

The properties get and set within the handler object are so-called traps.

They fire whenever a certain action on the object is registered.
You can follow @oliverjumpertz.
Tip: mention @twtextapp on a Twitter thread with the keyword “unroll” to get a link to it.

Latest Threads Unrolled: