Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct 'in' operator usage

Tags:

delphi

Consider the following procedure

procedure InTests;
var
  N, K: Integer;

begin
  N:= 1111;
  if N in [6, 8, 10]          // this is correct, readable and effective code
    then ShowMessage('OK');

  K:= 11;
  if N in [6, 8, 10, K]       // this is correct but less effective
    then ShowMessage('OK');   //  (compiler creates local 16-bytes set var)

  K:= 1111;
  if N in [6, 8, 10, K]       // this is a bug (K > 255)
    then ShowMessage('OK');
end;

in operator instead of if chain

  if (N = 6) or (N = 8) or (N = 10)
    then ShowMessage('OK');

makes the code more compact and readable, but Delphi documentation is silent about it, and you should be aware of potential problems.

The question is: should the in operator usage with constants only in brackets, for example

  if N in [6, 8, 10]
    then ShowMessage('OK');

be considered a good practice in Delphi?

like image 244
kludg Avatar asked Jan 29 '12 09:01

kludg


2 Answers

It is most definitely good practice. It makes the code far more readable and removes the need for logical operators, parentheses and so on. I would always use in for such a test.

The only drawback is Delphi's very limited support for sets (base ordinal type can have no more than 256 values). But where you are not bound by those limitations then you should have no hesitation in using in.

like image 122
David Heffernan Avatar answered Oct 16 '22 19:10

David Heffernan


What you have here is a set of byte. The question you should ask yourself is whether a set of byte is truly what your numbers represent? You have "magic numbers" here, and while I understand that it is just a sample, you must consider that while

 if Token in [TokenString, TokenNumber, TokenChar] then

...would be considered good practice, this:

 if N in [2, 12, 14, 19] then

...would be not.

However in the first case (named tokens), an explicit set type would be much more good practice:

 type TokenSet = ( TokenNone, TokenString, TokenChar,... )

Then the first sample is definitively a good practice.

like image 37
Kornel Kisielewicz Avatar answered Oct 16 '22 19:10

Kornel Kisielewicz