What pattern is this?

camelCase

The Case of the Mysterious Camel.
Reaction score
362
So, I had this problem where I had a class with a Vector2 instance which I wanted the class to have read-write access to internally but give other classes read access only.

My original solution (which was crap) was to pass a boolean into the Vector2's constructor that would indicate if it was read-only. If I called a set or any mutating method on a Vector2 that was read-only, it would not do anything and log that an illegal call was made. Then, to modify the read-only Vector2's values internally, I would have to create a new Vector2 instance.

I was really unhappy with this and tried to think of another solution and it finally hit me, so I did this:
Code:
public class Vector2 {
    public float x;
    public float y;
}
public class Vector2View {
    private final Vector2 m_Vector2;
    public float getX () { return m_Vector2.x; }
    public float getY () { return m_Vector2.y; }
    public Vector2View (Vector2 v) {
        if (v == null) { /*log this error*/ }
        m_Vector2 = v;
    }
}
public class SomeClass {
    private final Vector2     m_Position     = new Vector2();
    private final Vector2View m_PositionView = new Vector2View(m_Position);
    public Vector2View getPosition () {
        return m_PositionView;
    }
}

SomeClass can modify the position freely by modifying m_Position's x and y values but outside classes can only read the x and y values of the position by calling getX() and getY(). I felt it was particularly useful and used it a lot but I don't know what this pattern's called (if it even has a name).

I thought of the adapter pattern but that isn't right; this thing isn't about incompatible interfaces.
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
No real reason; just curious. Doesn't seem like Facade, though. Sure, same result as Facade, but different reasoning.
 

Accname

2D-Graphics enthusiast
Reaction score
1,462
Yeah, I cant think of anything which is more close to what you do.
But as a side note, why are you doing this? This is your program after all, you can just choose not to use it in a "wrong" way, cant you?
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
Yes, I can choose to but I might not always be so careful..
I fear my own carelessness =x
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
Sounds a like the proxy pattern. http://en.wikipedia.org/wiki/Proxy_pattern

This would be the right job for const, but alas - it's not in Java.

I think the typical Java way of doing this is to simply do

Code:
public Vector2 getPosition () {
        return new Vector2(m_PositionView);
}

Your viewer would have some strange side effects in edge cases by the way:

Code:
void someFunc(SomeClass someClass){
    Vector2View v = someClass.getPosition();
 
    someClass.setPosition( someOtherVector );
 
//Would now print the changed position of someClass and not the position at
//the time of calling getPosition();
    System.out.println( v );
}

Also, do you really want to get a Vector2View when asking for a position? Sounds ugly.
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
I don't see how that's a problem =P
I made both the Vector2 and Vector2View instance final.
Meaning, setPosition() would never change the instance of Vector2.
I foresaw that problem (paranoid about my carelessness again) and made sure both are final xD

Don't see what's so ugly about that; I quite much like it.
[Edit]
Proxy pattern looks to be right.
Wikipedia made it seem like it is only realistically used for saving memory but another site specifically mentioned access rights.
http://www.oodesign.com/proxy-pattern.html
However, the English was horrible there and I tend to think of English as an indicator of how reliable a source is =x

This source looks more reliable:
http://sourcemaking.com/design_patterns/proxy

A protective proxy controls access to a sensitive master object. The “surrogate” object checks that the caller has the access permissions required prior to forwarding the request.
Well, not quite what I'm doing but it's got the protective bit nailed.
 

s3rius

Linux is only free if your time is worthless.
Reaction score
130
Yes, but a Vector2 is hardly what I would call a "sensitive master object".

In your place I would just return a copy of the position vector. The JVM is highly optimized when it comes to small object creation.
See http://www.ibm.com/developerworks/java/library/j-jtp09275/index.html under Escape analysis.

Creating a proxy class for a simple vector class sounds like a nice idea if I want a constantly updating observer object to follow SomeClass' position without having to call getPosition() repeatedly.
But it sounds like massive overkill if I just want to know it's position once.

And the problem I outlined would manifest itself like this:

Say we have a nice little game. We want to keep the player moving, so we fire artillery at his position periodically. The impact location is indicated by a warning signal shortly before impact.

Code:
void fireAShell(Player p){
    Vector2View pos = p.getPosition();
 
    showWarningAt( pos );
 
    Thread.sleep(2000);
 
    putExplosion( pos );
}

We have a bunch of problems:

A) Vector2 and Vector2View are incompatible. methods like putExplosion() would have to be written for Vector2 and Vector2 parameters for full flexibility.
Also, you'd need comparison operations not only for Vector2<=>Vector2 but also for Vector2<=>Vector2View, Vector2View<=>Vector2 and Vector2View<=>Vector2View.

B) The explosion would occur at the place where the player is, not at the place where the warning is shown. The value of pos changes without the programmer doing anything with it. Isn't that what you actually wanted to stop?

C) Simply getting the position is very cumbersome:
Code:
Vector2 pos = new Vector2( p.getPosition().getX(), p.getPosition.getY() );

D) Not a very important point, but still to consider: It's not the normal way of doing things :)

I mean, if you still think it's worth it, then go ahead. But to me it feels like overcomplicating a simple thing.
 

camelCase

The Case of the Mysterious Camel.
Reaction score
362
Yeah, I'm well-aware of issue A.
I actually have three kinds of Vector2 classes.
Vector2, Vector2View and Vector2Readonly (read-only access after instantiation).

That's why I have a helper class that has overloads for all vector2 methods.
Overkill, for sure, but it's how I make them all compatible with each other. Unfortunately, I went to try and optimize away the Vector2 allocations and whatnot the moment I saw it was taking up almost 20% of the CPU time and the end result was this.. Thing.
Code:
public final class Vector2Ops {
    /*snip*/
    //{{Add
    public static void Add (float x1, float y1, float x2, float y2, Vector2 out) {
if (CompileConstants.Debug) {
if (Float.isNaN(x1)) {
Debug.e("x1 cannot be NaN");
return;
}
if (Float.isNaN(y1)) {
Debug.e("y1 cannot be NaN");
return;
}
if (Float.isNaN(x2)) {
Debug.e("x2 cannot be NaN");
return;
}
if (Float.isNaN(y2)) {
Debug.e("y2 cannot be NaN");
return;
}
}
out.x = x1+x2;
out.y = y1+y2;
}
//--Vector2-Vector2Readonly
public static void Add (Vector2 a, Vector2 b, Vector2 out) {
Add(a.x, a.y, b.x, b.y, out);
}
public static void Add (Vector2 a, Vector2Readonly b, Vector2 out) {
Add(a.x, a.y, b.x, b.y, out);
}
public static void Add (Vector2Readonly a, Vector2 b, Vector2 out) {
Add(a.x, a.y, b.x, b.y, out);
}
public static void Add (Vector2Readonly a, Vector2Readonly b, Vector2 out) {
Add(a.x, a.y, b.x, b.y, out);
}
//--Vector2-Vector2View
public static void Add (Vector2 a, Vector2View b, Vector2 out) {
Add(a.x, a.y, b.getX(), b.getY(), out);
}
public static void Add (Vector2View a, Vector2 b, Vector2 out) {
Add(a.getX(), a.getY(), b.x, b.y, out);
}
public static void Add (Vector2View a, Vector2View b, Vector2 out) {
Add(a.getX(), a.getY(), b.getX(), b.getY(), out);
}
//--Vector2Readonly-Vector2View
public static void Add (Vector2Readonly a, Vector2View b, Vector2 out) {
Add(a.x, a.y, b.getX(), b.getY(), out);
}
public static void Add (Vector2View a, Vector2Readonly b, Vector2 out) {
Add(a.getX(), a.getY(), b.x, b.y, out);
}
    //}}
    /*snip*/
}

As for issue B, I can see what you're getting at. I guess it depends on what the person using would expect getPosition() to do; does it return a new instance or the instance that the class holds?

If he expects a new instance, then the putExplosion() call would bug. If he expects the instance that the class holds; he would do this:
Code:
float x = someClass.getPosition().x;
float y = someClass.getPosition().y;
Thread.sleep(2000);
putExplosion(x, y);
You can see that getting the position required two lines of code instead of one and IS cumbersome (there is no way I would dare to deny that!) but that is if I didn't want to allocate a Vector2 class (because I feared; no longer, thanks to your research!).

Code:
Vector2 explosionPos = new Vector2(someClass.getPosition());
Thread.sleep(2000);
putExplosion(explosionPos);
Now, we get one line of code. Sure, we have to type a little more but this makes it explicit that we're actually recording the value of someClass' position before the Thread.sleep().

I guess it's more an issue of coding conventions, expectations and documentation.

What I was trying to prevent wasn't that. I was trying to prevent this from happening:
Code:
someClass.getPosition().x = 5.0f; //I want to prevent outside write access
I wanted to allow outside classes to read the actual values that the class was holding while making it impossible to directly modify the values because it might cause some data to go out of sync.
Code:
public class SomeClass {
    private final Sprite m_Sprite = new Sprite();
 
    private final Vector2 m_Position = new Vector2();
    private final Vector2View m_PositionView = new Vector2View(m_Position);
    public Vector2View getPosition () {
        return m_PositionView;
    }
    public void setPosition (float x, float y) {
        m_Sprite.setPosition(x, y);
        m_Position.x = x;
        m_Position.y = y;
    }
}
Modifying m_Position directly would cause the graphical representation and internal representation of the object's position to go out of sync (this isn't the problem I have in my game but the principle is the same).
With this,
Code:
Vector2View position = someClass.getPosition();
someClass.setPosition(100.0f, 0.0f);
System.out.println(position.toString());
The position will return 100.0f and 0.0f as it was updated (which is what I like). If this were C++ I would expect "position" to be whatever the previous value is because C++ returns by value unless pointers or references are involved. However, this is Java where it returns by references and I would expect a reference to an object's position to report the object's position, even if it changes.

Well, that's my rationale behind it, anyway.

As for issue C, I could just add a constructor to Vector2 to accept Vector2View =P
Code:
public Vector2 (Vector2View v) { x=v.getX(); y=v.getY(); }

As for issue D, yes, I do acknowledge that it might not be the normal way. I say "might" because I have no experience with the standard coding conventions where Java is concerned. I know the syntax but I don't know the, uh, culture of Java.

If returning a new instance really is the Java way, then I doggone messed up =P

[Edit]
Ignore the poorly formatted code, I think it just deleted all my tab characters.
 
General chit-chat
Help Users
  • No one is chatting at the moment.
  • The Helper The Helper:
    So what it really is me trying to implement some kind of better site navigation not change the whole theme of the site
  • Varine Varine:
    How can you tell the difference between real traffic and indexing or AI generation bots?
  • The Helper The Helper:
    The bots will show up as users online in the forum software but they do not show up in my stats tracking. I am sure there are bots in the stats but the way alot of the bots treat the site do not show up on the stats
  • Varine Varine:
    I want to build a filtration system for my 3d printer, and that shit is so much more complicated than I thought it would be
  • Varine Varine:
    Apparently ABS emits styrene particulates which can be like .2 micrometers, which idk if the VOC detectors I have can even catch that
  • Varine Varine:
    Anyway I need to get some of those sensors and two air pressure sensors installed before an after the filters, which I need to figure out how to calculate the necessary pressure for and I have yet to find anything that tells me how to actually do that, just the cfm ratings
  • Varine Varine:
    And then I have to set up an arduino board to read those sensors, which I also don't know very much about but I have a whole bunch of crash course things for that
  • Varine Varine:
    These sensors are also a lot more than I thought they would be. Like 5 to 10 each, idk why but I assumed they would be like 2 dollars
  • Varine Varine:
    Another issue I'm learning is that a lot of the air quality sensors don't work at very high ambient temperatures. I'm planning on heating this enclosure to like 60C or so, and that's the upper limit of their functionality
  • Varine Varine:
    Although I don't know if I need to actually actively heat it or just let the plate and hotend bring the ambient temp to whatever it will, but even then I need to figure out an exfiltration for hot air. I think I kind of know what to do but it's still fucking confusing
  • The Helper The Helper:
    Maybe you could find some of that information from AC tech - like how they detect freon and such
  • Varine Varine:
    That's mostly what I've been looking at
  • Varine Varine:
    I don't think I'm dealing with quite the same pressures though, at the very least its a significantly smaller system. For the time being I'm just going to put together a quick scrubby box though and hope it works good enough to not make my house toxic
  • Varine Varine:
    I mean I don't use this enough to pose any significant danger I don't think, but I would still rather not be throwing styrene all over the air
  • The Helper The Helper:
    New dessert added to recipes Southern Pecan Praline Cake https://www.thehelper.net/threads/recipe-southern-pecan-praline-cake.193555/
  • The Helper The Helper:
    Another bot invasion 493 members online most of them bots that do not show up on stats
  • Varine Varine:
    I'm looking at a solid 378 guests, but 3 members. Of which two are me and VSNES. The third is unlisted, which makes me think its a ghost.
    +1
  • The Helper The Helper:
    Some members choose invisibility mode
    +1
  • The Helper The Helper:
    I bitch about Xenforo sometimes but it really is full featured you just have to really know what you are doing to get the most out of it.
  • The Helper The Helper:
    It is just not easy to fix styles and customize but it definitely can be done
  • The Helper The Helper:
    I do know this - xenforo dropped the ball by not keeping the vbulletin reputation comments as a feature. The loss of the Reputation comments data when we switched to Xenforo really was the death knell for the site when it came to all the users that left. I know I missed it so much and I got way less interested in the site when that feature was gone and I run the site.
  • Blackveiled Blackveiled:
    People love rep, lol
    +1
  • The Helper The Helper:
    The recipe today is Sloppy Joe Casserole - one of my faves LOL https://www.thehelper.net/threads/sloppy-joe-casserole-with-manwich.193585/

      The Helper Discord

      Members online

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top