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:
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.
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.