I'm developing a game that often has repetitious code that I can't simplify.Example of what I do normally:Square object;GL11.glPushMatrix();   // Pushes a matrix stack down by one. This allows us to rotate our object freely GL11.glTranslated(object.x, object.y, 0); // Move object to its positionobject.drawToScreen(); // Draws the objectGL11.glPopMatrix();    // Pushes a matrix stack up by one, prevents the translation from affecting other objects in the sceneThe above code gets bulky and needs to be repeated often.What I want to do:Square object;bumpMatrix(){ // implies GL11.glPushMatrix();   GL11.glTranslated(object.x, object.y, 0); // Move object to its positionobject.drawToScreen();  // Draws the object} // implies GL11.glPopMatrix();Is there a way to make this happen? I swear I've seen something like it somewhere before in Java. It would allow me to make a single function and not have to Copy/Paste the same group of code several times, just call that function.
Make functions that imply other functions
java;syntax;opengl
It's similar to the RAII idiom in C++, where you put resource management code in the constructor & destructor of a class. Since Java doesn't have destructors, if you're targeting Java 7 or later you could instead (ab)use try-with-resources and an AutoCloseable (untested):class GLCoordGuard implements AutoCloseable {    protected GL _gl;    public Manager(GL gl) {        _gl = gl;        gl.glPushMatrix();    }    public void close() {        _gl.glPopMatrix();    }}...    Square object;    try (GLCoordGuard guard = new GLCoordGuard(GL11)) {        GL11.glTranslated(object.x, object.y, 0); // Move object to its position        object.drawToScreen(); // Draws the object    }The syntax in the question resembles Ruby's blocks, which get packaged in a Proc object and passed to a function, which can invoke it whenever it likes. You can do something similar in Java by passing a lambda (which require Java 8) to another function (untested):public void bumpMatrix(Function<Void,Void> glOps) {    GL11.glPushMatrix();    glOps.apply(null);    GL11.glPopMatrix();}...    Square object;    bumpMatrix((Void unused) -> {        GL11.glTranslated(object.x, object.y, 0); // Move object to its position        object.drawToScreen(); // Draws the object    });