Three Tips to Make Code Nicer


  Posted on 22 Oct 2015

1.Abstract common parts

When you see two blocks of code are similar to each other, it means you need to abstract them into a function and call it twice. For example, let us see the following code.

int sum1 = 0;
for (int i = 0; i < n; i++)
{
	sum1 += f[i];
}

int sum2 = 0;
for (int i = 0; i < m; i++)
{
	sum2 += g[i];
}

This code is calculating the sum of array f[] and array g[]. It would be better to change it like this.

int get_sum(int f[], int n)
{
	int ret = 0;
	for (int i = 0; i < n; i++)
	{
		ret += f[i];
	}
	return ret;
}

int sum1 = get_sum(f, n);
int sum2 = get_sum(g, m);

This change is not only make it better to read, but also make it better to debug especially when they share a big block of code. Every time you want to debug or fix this block of code, you only need to do it once in the function. It saves the trouble of inconsistancy between the original two blocks of code.

2.Avoiding complicated if structures

The following code uses a very complicated logic with booleans.

if (a)
{
	if (b)
	{
		return true;
	}else
	{
		return false;
	}
}else
{
	if (b)
	{
		return c;
	}else
	{
		return false;
	}
}

Instead of use quoted if, we should first try to extract some independent situations and handle them first. This will relief the burden of handling them all together.

The following code does the same thing as the above. First, we can see that no matter what is a and c. If b is false, then the final result is false. So we handle this first. After that we can just assume b is true. So the rest of the work would be much easier.

if (!b)
{
	return false;
}
if (a)
{
	return true;
}
return c;

3.Use subroutines

First, let’s see an example of using subroutines to avoid breaking multiple quoted loops. Given a 2-dimentional matrix. We want to find a character in the matrix and print its coordinate. If we do not use subroutines, we can do it like this.

bool multi_break = false;
for (int i = 0; i < row_num; i++)
{
	for (int j = 0; j < col_num; j++)
	{
		if (matrix[i][j] == target)
		{
			x = i;
			y = j;
			multi_break = true;
			break;
		}
	}
	if (multi_break)
		break;
}
cout << x << " " << y << endl;

If we use subroutine, we can do it much more elegant.

pair<int, int> find(int target)
{
	for (int i = 0; i < row_num; i++)
	{
		for (int j = 0; j < col_num; j++)
		{
			if (matrix[i][j] == target)
			{
				return make_pair(x, y);
			}
		}
	}
}

void main()
{
	pair<int, int> a = find(target);
	cout << a.first << " " << a.second << endl;
}