How to set the value of the result?

function MyFunc: Boolean;
begin
    if eval then
    Result := True
    else
        Result := False;

    /* Note it a fancy example, I know that in this case I can do: Result := Eval */
end;

OR

function MyFunc: Boolean;
begin
    Result := False;

    if eval then
        Result := True;

/* good by else statement */

end;
+3
source share
7 answers

It really depends on the complexity of the method, you should always strive for readability, these examples are great for me.

function MyFunc: Boolean;
begin
   Result := False;
   if (Something or SomethingElse) and Whatever then
     Result := True;
end;


function MyFunc: Boolean;
begin
  Result := (Something or SomethingElse) and Whatever;
end;


function MyFunc: Boolean;
begin
   Exit((Something or SomethingElse) and Whatever);
end;

function MyFunc: Boolean;
begin
  if (Something or SomethingElse) and Whatever then
     Result := True
  else
     Result := False;
end;

Personally, I would like to avoid other statuses and write as few lines of code as possible, so I would go with example 2, but example 1 is fine too, options 3 and 4 are not very readable by IMO.

I think that if you give these 4 examples to beginners, the first one will be easiest to understand.

+8
source

Why not use.

function MyFunc: Boolean;
begin
    Result := eval;
/* good by if-else statement */
end;

The result is the same with any of the three options. Performance wise basically no different.

. , if

+3

, , "" , , , . .

+1

,

if eval then
begin
  // yada yada
  Result := True
end
else    
  Result := False;

, , :

Result := eval;

, , , . , . :

for i := 0 to Length(aArray) - 1 do
  if Assigned(aArray[i]) then
    Inc(AssignedCounter);

, :

for i := 0 to Length(aArray) - 1 do
  Inc(AssignedCounter, Ord(Assigned(aArray[i])));
+1

This is the real answer - you just set the result for the value :)

Note that you can use the result as a normal variable inside the function.

eg.

function DoSomeStuff: Boolean;
Begin
  Result := (evaulate some conditions);
  if Result then
  begin
   //Do good stuff
  end;
end; 
0
source

I use the second method when the function has a lot:

 if (...) then
 begin
   [...]
   result := default_value;
   exit
 end;

check (or errors). I do not want to repeat " result := default_value;" in each case.

0
source

you can also do MyFunc: = true; which has the same meaning as Result: = true;

-1
source

Source: https://habr.com/ru/post/1710910/


All Articles