简体   繁体   中英

More elegant way to update index into circular list?

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?

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.

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.

There's no need for the conditional operator

 CurrentQuestion = ++CurrentQuestion % questions.Length;

but I guess which one you prefer is a matter of style more than anything else

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM