Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way to update index into circular list?

Tags:

c#

I have a list of questions that the user will iterate through, they can start at any question, but they do have a order to them, so in order to do this I just maintain an index into the array and increment it like so:

CurrentQuestion = (++CurrentQuestion < questions.Length) ? CurrentQuestion : 0;

It isn't necessarily obvious what is happening here, is there a more elegant way to do this?

like image 520
NominSim Avatar asked Dec 06 '22 13:12

NominSim


2 Answers

I have a strong aversion to using ++ on a variable and then that variable again in the same statement. I believe this line works fine in C#, but lines like this are undefined in C/C++, and so they raise a flag for me. I would prefer

CurrentQuestion = (CurrentQuestion+1) % questions.Length;

Which I think of as the idiomatic way of doing clock-arithmetic in C-like languages.

like image 104
Lou Franco Avatar answered Dec 23 '22 03:12

Lou Franco


It isn't necessarily obvious what is happening here, is there a more elegant way to do this?

While it's not immediately obvious to some, I know exactly what that's doing.

However, what you may want to consider is that it's more important to write readable code than it is to be clever. Code has to be maintained, and you are NOT smarter than the compiler.

Write the code like thus, and be happy with it:

//ensure that the CurrentQuestion counter increments and loops back around after hitting "list max"
CurrentQuestion = CurrentQuestion + 1;
if (CurrentQuestion >= questions.Length) {
  CurrentQuestion = 0;
} // meta-comment: use braces incase you have to add more later

The important bit is that this code is now readable, and it's still optimized. It does exactly what the other code does, and we can change parts later without a lot of re-reading of the code.

Also note some semantics I used here.

  • Always use the braces, even when you don't think you need them.
  • Do CurrentQuestion = CurrentQuestion + 1; instead of either CurrentQuestion += 1; or CurrentQuestion++; or ++CurrentQuestion; because the first is much more explicit on intent. Always write intentful code.
like image 24
jcolebrand Avatar answered Dec 23 '22 02:12

jcolebrand