I dunno why I read [icode]vars[/icode] as [icode]wars[/icode] in the title at first, but here are my opinions in that regard. Note that I have changed my style, after coming to know of the 64k method limit on android, but I like this new style, as this is more simple.
Rule #1: Prefer to use public variables when they make sense
For example, take a class which is only a container of data, such as a [icode]Vector2[/icode]. Then it is better to leave the variables x and y as public. Using setters and getters is not a good option because it’s not clean.
// Clean way, using public variables.
speed.x += 4;
// Not so clean when you use getters and setters
speed.setX(speed.getX() + 4);
Using getters and setters like this will make your code look complex. However do this only when you need no validation on the variables, like in this case. It is a simple data class so keep them as public.
Rule #2: For objects that don’t need to be set, consider using [icode]final[/icode] and public.
For example, you have to write a class that has a property called position, and it is of type [icode]Vector2[/icode]. Now you want your users to be setting its contents and not itself directly. Use the final keyword here, and initialize it once in the constructor.
// This works, and you intend to do this simply.
entity.position.x += 4;
// But this will give an error if you try to assign it.
@@entity.position = new Vector2();
// And you just do this in the class, pretty simple.
public final Vector2 position = new Vector2();
This gives a benefit that you do not need to evaluate the variable each time for being null, and we can enjoy the simplicity too. Keep in mind that getters and setters are needed if the data requires validation.
Rule #3: Use Getters in case you need the value to be readonly to users and not in that same class.
Yes, in case you are needed to set the value of the variable internally and prevent the user from accessing it, use a getter and make it private or protected. For example, you can do this for FPS value from the game loop so the user is able to get the fps but not set it.
Rule #4: Use Setters in case you need data verification.
Yes, I don’t say never use setters, you have to use them when you really need and this is one of such areas. Consider that you have to set a value, like the volume of the playing sound, and it should be in a range.
public void setVolume(float volume)
{
this.volume = Math.min(1, Math.max(volume, 0));
}
These are the four basic rules that I’ve taught myself recently after reading a lot of sample android code, and they work great for me so I do recommend them to you. Additionally this removes the function call overhead, as I heard (but am not sure) that invoking virtual functions causes some overhead.