이전에 배열 주소와 크기를 인자로 받아서 퀵소트 알고리즘으로 정렬하는 코드를 작성했다.

책 '클린 코드'에서 배운 교훈을 적용해서 리팩토링 해보았다.

1. 클린 코드에서 얻은 가르침 3가지

이름_의도를 분명히 밝혀라(명확한 이름)

함수_서술적인 이름을 사용하라!

함수_작게 만들어라!

2. 코드 고치기

고치기 전의 코드

void	set_array_quick_sorted(int *array, int size)
{
	int	pivot = array[size / 2];

	int	tmp;
	int	i = 0;
	int	j = size - 1;
	while (i < j)
	{
		while (array[i] < pivot)
			i++;
		while (array[j] > pivot)
			j--;
		if (i >= j)
			break ;
		tmp = array[i];
		array[i] = array[j];
		array[j] = tmp;
	}

	if (size > 2)
	{
		int	index_pivot = -1;
		int	tmp_size;
		while (tmp_size--)
		{
			if (array[++index_pivot] == pivot)
				break ;
		}
		set_array_quick_sorted(array, index_pivot);
		set_array_quick_sorted(&(array[index_pivot]), size - index_pivot);
	}
}

고친 이후의 코드

static void	swap_array_indexes(int *array, int idx_front, int idx_behind)
{
	int	tmp;

	tmp = array[idx_front];
	array[idx_front] = array[idx_behind];
	array[idx_behind] = tmp;
}

static void	partition_array_by_pivot(int *array, int size, int val_pivot)
{
	int	idx_front;
	int	idx_behind;

	idx_front = 0;
	idx_behind = size - 1;
	while (idx_front < idx_behind)
	{
		while (array[idx_front] < val_pivot)
			idx_front++;
		while (array[idx_behind] > val_pivot)
			idx_behind--;
		if (idx_front >= idx_behind)
			break ;
		swap_array_indexes(array, idx_front, idx_behind);
	}
}

static int	get_index_pivot(int *array, int pivot, int size)
{
	int	ret_index;

	ret_index = -1;
	while (size--)
		if (array[++ret_index] == pivot)
			break ;
	return (ret_index);
}

void	set_array_quick_sorted(int *array, int size)
{
	int	value_pivot;
	int	index_pivot;

	value_pivot = array[size / 2];
	partition_array_by_pivot(array, size, value_pivot);
	if (size > 2)
	{
		index_pivot = get_index_pivot(array, value_pivot, size);
		set_array_quick_sorted(array, index_pivot);
		set_array_quick_sorted(&(array[index_pivot]), size - index_pivot);
	}
}

3. 고려한 사항들

  1. 함수를 쪼개고 분리하여 작게 만들었다.

  2. 더 작게 쪼개어 추상화된 함수의 이름을 서술적으로 나타냈다.

  3. 좀 더 명확한 이름으로 나타내고자 값을 서로 비교하는 인덱스에 각각 front와 behind를 붙였다.

3-1) 인덱스에 front나 behind를 붙여서 길게 만드는게 마음에 걸렸지만 퀵소트는 특수한 경우이므로 명확하게 작성했다.