Proxy Classes
Created: 25th May 2026
Updated: 25th May 2026
A bit of a short post but still an important concept to cover. When dealing
with custom data we may create functions to access certain values. Sometimes,
we want to make some guarantees when accessing a object, like ensuring the
right values are initialized. Other times, we just want to make the access
of an object more syntatically "satisfying" or logical.
For the first example, I would like to guarantee that a pointer exists before
I attempt to run a function through it. Usually, we would have a null check
for said pointer or some sort of try-catch. Instead, we can use a proxy class
of the base class that we are attempting to call. Let's pretend my base class
has a "Backflip" function that requires an animation. I then create a proxy class
and calls it's constructor, but I forgot to add the animation. If I were to
call the proxy class, it should first check whether if there is an animation.
If there isn't one, it will call the base class to help generate the animation.
To simplify, instead of having to generate the animation itself, it passes that
responsibility back to the base class. This is similar to having a wrapper
for classes that you don't want to touch but still need to modify or read values
from.
For the second example, I am using a flattended 2D array, a 1D array that
is made rows and columns in mind. Normally, if the 2D array was actually
allocated using 2 dimensions, accessing a value/element would be using the
subscript operator like this to access the first row, first column: [0][0].
However, if I were to use a 1D array, which generally is better since allocation
is much easier to write, I would have to do some math to show it. And also,
if my 2D array data is private, a user of my class would not be able to
use the subscript operator, and I would have to implement a function to
read or modify any values, such as arr.get(0,0). This isn't bad necessarily
and sometimes it's good to be explicit. However, the idea of the class is
rather simple and we should also have a simple way to access it's data.
On the first glance, it would make sense to overload double subscript operator.
But that does not exist, so instead we have a subscript operator that returns
a proxy class, which itself has a subscript overload that returns a value.
This syntatically would look like "arr[0][0]", but when broken down is more like
"[arr.get_row(0)].get_column(0)". Instead of having a base class handle all
the responsibility, pass it on to the proxy to do the second layer of searching.
As I said, a rather short post. But thank you for reading once again.
Have a pleasant day, see you in the next post.