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,463
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.
  • Ghan Ghan:
    Still lurking
    +3
  • The Helper The Helper:
    I am great and it is fantastic to see you my friend!
    +1
  • The Helper The Helper:
    If you are new to the site please check out the Recipe and Food Forum https://www.thehelper.net/forums/recipes-and-food.220/
  • Monovertex Monovertex:
    How come you're so into recipes lately? Never saw this much interest in this topic in the old days of TH.net
  • Monovertex Monovertex:
    Hmm, how do I change my signature?
  • tom_mai78101 tom_mai78101:
    Signatures can be edit in your account profile. As for the old stuffs, I'm thinking it's because Blizzard is now under Microsoft, and because of Microsoft Xbox going the way it is, it's dreadful.
  • The Helper The Helper:
    I am not big on the recipes I am just promoting them - I use the site as a practice place promoting stuff
    +2
  • Monovertex Monovertex:
    @tom_mai78101 I must be blind. If I go on my profile I don't see any area to edit the signature; If I go to account details (settings) I don't see any signature area either.
  • The Helper The Helper:
    You can get there if you click the bell icon (alerts) and choose preferences from the bottom, signature will be in the menu on the left there https://www.thehelper.net/account/preferences
  • The Helper The Helper:
    I think I need to split the Sci/Tech news forum into 2 one for Science and one for Tech but I am hating all the moving of posts I would have to do
  • The Helper The Helper:
    What is up Old Mountain Shadow?
  • The Helper The Helper:
    Happy Thursday!
    +1
  • Varine Varine:
    Crazy how much 3d printing has come in the last few years. Sad that it's not as easily modifiable though
  • Varine Varine:
    I bought an Ender 3 during the pandemic and tinkered with it all the time. Just bought a Sovol, not as easy. I'm trying to make it use a different nozzle because I have a fuck ton of Volcanos, and they use what is basically a modified volcano that is just a smidge longer, and almost every part on this thing needs to be redone to make it work
  • Varine Varine:
    Luckily I have a 3d printer for that, I guess. But it's ridiculous. The regular volcanos are 21mm, these Sovol versions are about 23.5mm
  • Varine Varine:
    So, 2.5mm longer. But the thing that measures the bed is about 1.5mm above the nozzle, so if I swap it with a volcano then I'm 1mm behind it. So cool, new bracket to swap that, but THEN the fan shroud to direct air at the part is ALSO going to be .5mm to low, and so I need to redo that, but by doing that it is a little bit off where it should be blowing and it's throwing it at the heating block instead of the part, and fuck man
  • Varine Varine:
    I didn't realize they designed this entire thing to NOT be modded. I would have just got a fucking Bambu if I knew that, the whole point was I could fuck with this. And no one else makes shit for Sovol so I have to go through them, and they have... interesting pricing models. So I have a new extruder altogether that I'm taking apart and going to just design a whole new one to use my nozzles. Dumb design.
  • Varine Varine:
    Can't just buy a new heatblock, you need to get a whole hotend - so block, heater cartridge, thermistor, heatbreak, and nozzle. And they put this fucking paste in there so I can't take the thermistor or cartridge out with any ease, that's 30 dollars. Or you can get the whole extrudor with the direct driver AND that heatblock for like 50, but you still can't get any of it to come apart
  • Varine Varine:
    Partsbuilt has individual parts I found but they're expensive. I think I can get bits swapped around and make this work with generic shit though
  • Ghan Ghan:
    Heard Houston got hit pretty bad by storms last night. Hope all is well with TH.
  • The Helper The Helper:
    Power back on finally - all is good here no damage
    +2
  • V-SNES V-SNES:
    Happy Friday!
    +1
  • The Helper The Helper:
    New recipe is another summer dessert Berry and Peach Cheesecake - https://www.thehelper.net/threads/recipe-berry-and-peach-cheesecake.194169/

      The Helper Discord

      Members online

      No members online now.

      Affiliates

      Hive Workshop NUON Dome World Editor Tutorials

      Network Sponsors

      Apex Steel Pipe - Buys and sells Steel Pipe.
      Top