3

A while loop can be written as follows in C# (and many other languages):

int someValue;
int someTerminatingValue;

while ((someValue = GetSomeValue()) != someTerminatingValue)
{
    // Do something interesting
}

Is there a name for this pattern of assigning the value inside the while loop's expression?

NB I'm not asking if it is a good idea or a bad idea, just if there's a name for this pattern. Whether it's good or bad, people will see it so they need to know what it is. If there isn't a name for it then that's fine, I'm just asking if there is one.

BanksySan
  • 724

2 Answers2

5

There is no name for this specific idiom.

And it's a good idea™ to write idiomatic code, instead of trying to dumb it down further or writing code which is too clever by half.

Especially if any alternatives are long-winded, tedious, repetitive or otherwise bad.

Deduplicator
  • 9,209
2

Idiom

At this scale, reoccurring motifs are called idioms rather than design patterns. The design patterns work on a larger scale than just a single line of code or a single loop.

Clever code

This would also qualify as clever code anti-pattern. Clever code is not advisable, because it will be harder to read for your teammates and for yourself 6 moths later.

Better alternatives

Loop initialization, loop "propulsion", loop exit conditions are separated.

    int someValue;
    int someTerminatingValue;

    for (someValue = GetSomeValue();         // initialize the loop variable
         someValue = GetSomeValue();         // move the loop onward
         someValue != someTerminatingValue)  // exit condition
    {
        // Do something interesting
    }

But this is still clever code. McConnell call this "a while loop abusively crammed into a for loop header" (see Code Complete 2, p.374). he also proposes a better alternative.

    someValue = GetSomeValue();                 // initialize the loop variable
    while (someValue != someTerminatingValue)   // exit condition
    {
        // Do something interesting
        someValue = GetSomeValue();             // move the loop onward
    }

Related:

enter image description here (source)

Nick Alexeev
  • 2,532