티스토리 뷰

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

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

 

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);
	}
}

 

고려한 사항들

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

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

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

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

 

 

좀 더 생각해 볼 것들

1) size가 2보다 클 때 실행되는 코드들을 더 작게 추상화해서 나타내야할지 고민이다.

2) get_index_pivot 함수에서 return할 변수 이름을 선언할 때 앞에 ret 을 붙였다. 독자에게 미리 return할 변수를 알려주는 목적으로 넣었는데 어떻게 받아들일지 확실치 않다. 내가 읽어보기에는 ret이 붙은 변수를 더 주의깊게 보게되고 다시 위로 올라가서 변수를 확인하지 않아도 되어서 편했다. 독자들의 피드백을 직접적으로 받아보면서 최적화해야겠다. 쳐 맞으면서 배우는거다.

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함