Note: I don’t talk about sharing variables between Activities or the need to save them permanently.
I’m developing an app that uses a 3D-Engine. All my rendering takes place in one renderer class. I have several objects (such as a camera, a light, a framebuffer) which I need in several methods and have therefore declared them as class members:
public class Renderer{
//..
private Camera camera = null;
private Light sun = null;
private Matrix someMatrix = new Matrix();
private void onSurfaceChanged(GL10 gl, int width, int height){
//...
sun = new Light(x,y,z,color);
camera = new Camera(arg1, arg2);
}
public void onDrawFrame(GL10 arg0) {
someMatrix = getRandomValues();
//...
}
}
Is this the “correct” way to do this? Or should I rather pass the objects via method arguments? Of course I could declare someMatrix also in onDrawFrame, but since resources are not plentyful on mobile devices, I rather not have them initialized each time onDrawFrame is called. The problem I have now, is that I really have a lot class variables, which I normally would consider as bad style. I couldn’t find anything about this topic in the style guidelines for Android. Are there alternatives which improve readability and/or safety?
This is the correct way of doing so, yes.
Nothing more to add, really.