Keeping Index Within Bounds

Issue

We often have to deal with a list of items while managing its selected index. This is a fairly common pattern and one not too difficult to accomplish. But such a common and simple pattern are frequently written in more line of codes then necessary.

The bulk of the codes come from the need to guard against situation where index might goes out of bounds. Generally, a variable is being used to track the selected index. Obviously the selected index have to be within the bounds of the list. How would you write it?

We can drop bounds guard everywhere and things will just work. My challenge to you is to write it in the least amount of code. If you actually follow me up until here, I believe you are someone who care about code quality and I am going to share with you my approach.

My approach

The key is to clamp the selected index within the bounds upon setting it. Clamp function generally expand to a series of if else statements, but a more descriptive way to describe the behavior of clamp is as follow:

void set_selected_index(int the_selected_index) {
	int lower_bound = 0;
	int upper_bound = MAX(lower_bound, total_number_of_items_in_list - 1);
	the_selected_index = MAX(lower_bound, MIN(the_selected_index, upper_bound));
	if (selected_index != the_selected_index) {
		selected_index = the_selected_index;
		set_need_update();
	}
}

The first 3 line effectively clamp the_selected_index within the bounds, follow by a guard to notify the need to update only if there are changes.

This function is extremely robust and can take quite a beating, for example:

void next() {
	set_selected_index(selected_index + 1);
}

void previous() {
	set_selected_index(selected_index - 1);
}

The above 2 functions will generally be bind to controls for a user to tap on. No matter how many times the user tap on both buttons, the user will not get out of bounds and only feedback appropriately when there are changes.

Pretty neat huh?