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.
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:
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:
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?