While select firstonly

October 22, 2009 at 22:11
filed under Dynamics AX

Some months ago, I had this ‘aha! moment’, when I saw something like this in my code:

while select firstonly custTable
    // do something

I had modified a singe select statement into a loop, but forgot to remove the ‘firstonly’ qualifier.
Then it hit me that the over example is actually the same as writing the following:

select firstonly custTable;

    // do something

I really liked the idea of the while loop, and I think I’ve used it once or twice where I thought it was appropriate, until I bothered Googling the statement. You get 9 results from Google, which isn’t much, and the first is on msdn:

Do not use while select firstOnly.

However, this result is followed by 2 others from msdn (1 and 2), where they do use “while select firstonly”. The last one, is on a page titled “Top Best Practices to Consider”.

I can think of a couple of reasons why you shouldn’t use such a statement, one of which is performance, and an other readability, but apparently, Microsoft uses it anyway. Also, you can’t use it in cases where you need an ‘else’ branch.

I, for one, have changed my code and won’t be writing code like this anymore. “While select firstonly” was short lived.


RSS / trackback

  1. Luegisdorf

    Hi Klaas

    I think, the capital reason why best practice does deny the use of ‘while select firstonly’ is the readablity. I don’t think it’s a performance issue.

    But I like the idea to have the exists condition for free as you have discovered.

    I just would recommend to comment that statement to make clear what the meaning of the code was, like:

    // find firstonly and do some stuff if found
    while select firstonly myTable

    Thank you for this article and
    best regards

  2. Malcolm Burtt

    I think that the reason that they say not to use “while select firstOnly” stems from the note that appears alongside the X++ best practice advice about using “select firstOnly”. It says…

    “The firstOnly qualifier does not guarantee that only one record is returned.”

    and then this is immediately followed by the statement…

    “Do not use while select firstOnly.”

    …the two things are linked.

    If you use “while select firstOnly” you may write code that assumes that only one record will be processed by the while loop (i.e. that there will be only one iteration and that the loop will immediately exit after that one iteration). In fact there is no way to be sure that only one iteration will occur. Even if you write your code knowing that more than one iteration might occur someone else might later make the mistake of assuming firstOnly means just one iteration.