I’m trying to further develop the coding standards I’m using for my game engine, and I want other peoples input. It’s not a typical standard, I kind of made it up to fit games and multiple languages.
Here are techniques I use:
- Public Field Access
[list]
[li]most fields should be publicly accessible, using the getter/setter approach is often unnecessary for games (it is necessary when classes implement interfaces) - getters/setters only exist for interfaces or for developers who like using them
[/li] - Reference Immutability
[li]public fields tend to be final so the reference to that field can be passed around
- if a public field is not final, it is meant to hold the reference to a field on an entity with a final field
[/li] - Memory Model Nescient
[li]methods that typically return non-primitive values have a reference to the return type as the last argument of the method
- avoid calling new at all costs, use memory managers (interface with alloc/free) which the user defines (either pooling objects or not pooling objects)
[/li]
[/list]
Here’s an example of a class:
public class Sprite implements Positioned, Angled
{
public final Vec2f position = new Vec2f(); // read-only refence
public final Vec2f offset = new Vec2f(); // read-only reference
public final Scalarf angle = new Scalarf(); // read-only reference
private final Matrix2f matrix = new Matrix2f(); // hidden field
public final Memory<Particle> particleMemory;
private Particle[] particles = new Particle[ 1024 ];
private int particleCount;
public void burst( int n) { // uses memory implementation to handle allocation
while (--n >= 0) {
particles[particleCount++] = particleMemory.alloc();
}
}
public void free( int n ) { // uses memory implementation to handle freeing
while (--n >= 0 ) {
memory.free( particles[--particleCount] );
particles[particleCount] = null;
}
}
public void setPosition(Vec2f pos) { // set by-value
this.position.set( pos );
}
@Override
public Vec2f getPosition() { // get-by-reference
return position;
}
public void setAngle(float angle) { // set-by-value
this.angle.v = angle;
}
@Override
public float getAngle() { // get-by-value
return angle.v;
}
public Vec2f getActualPosition(Vec2f out) { // get computed value
out.set( position );
out.rotate( angle );
return out;
}
public Matrix2f getMatrix( Matrix2f out ) { // get hidden field
out.set( matrix );
return out;
}
public Vec2f transform( Vec2f out ) { // get computed value from hidden field
matrix.transform( out );
return out;
}
public Particle[] getParticles() {
return particles;
}
public int getParticleCount() {
return particleCount;
}
}
This obviously isn’t a real life class.
What are your personal preferences? I’m still developing this, I go back and forth often because I never know what people really prefer.