Refactoring and code readability

Today I’m going to write a post about how refactoring is useful to increase the readability (and thus, maintainability) of the code.

I will start with a basic example: tinyGL uses a struct called V3 to represent three dimensional vectors:

struct V3 {
	float v[3];
};

The APi also defines some functions to work with vectors (namely construction, function to get the normal vector, multiplication, copy, etc)

V3 gl_V3_New(float x, float y, float z);
int gl_V3_Norm(V3 *a);
void gl_MulM3V3(V3 *a, const M4 *b, const V3 *c);
void gl_MoveV3(V3 *a, const V3 *b);

Which in turn leads to code like this:

V3 a, b;
a = gl_V3_New(5,5,5);
M4 transform;
gl_MulM4V3(b,transform,a);

My goal with this refactoring is to increase the readability by introducing a class Vector3, which will make creating vectors and using the much easier (I also plan to write classes that represent matrices so that operations between vector and matrices can be expressed in a much concise and intuitive way)

class Matrix4 {
  public:
	Matrix4();
	Matrix4(const Matrix4 &other);
 
	Matrix4 operator=(const Matrix4 &other);
	Matrix4 operator*(const Matrix4 &b);
	static Matrix4 identity();
 
	Matrix4 transpose() const;
	Matrix4 inverse_ortho() const;
	Matrix4 inverse() const;
	Matrix4 rotation() const;
 
	Vector3 transform(const Vector3 &vector) const;
	Vector4 transform(const Vector4 &vector) const;
  private:
	float m[4][4];
};

class Vector3 {
  public:
	Vector3();
	Vector3(const Vector3 &other);
	Vector3(float x, float y, float z);
	Vector3 operator=(const Vector3 &other);
 
	static Vector3 normal(const Vector3 &v);
 
	Vector3 operator*(float value);
	Vector3 operator+(const Vector3 &other);
	Vector3 operator-(const Vector3 &other);
 
  private:
	float v[3];
};

Those changes would make that previous snippet look like this:

Vector3 a(5,5,3);
Matrix4 transform;
Vector3 b = transform.transform(a);

As we can see from this little snippet the code is more readable, plus now that vectors are represented by classes we can also overload binary operators such as + and – to express vector addition and subtraction in a more concise way (instead of having to write the addition separately for each component).

That’s all for now! I will try to update the blog again this week to show more examples.