What may be confusing you is that the code of that function, Tschool.Accepted
is obviously incomplete; a value is assigned to the result value of the function if the if
statement is true, but not otherwise. That's actually a programming error, because it means that the result value is undefined if the if
statement returns false.
Put another way, what's wrong with Tschool.Accepted
is that it breaks the fundamental rule that every execution path through the function should result in the function's result being assigned a value. As written, Tschool.Accepted
breaks the rule because it doesn't get a result value assigned if the if ...
condition is false.
So, one way to correct the programming error is to add an else
clause to the end of the if ...
statement, e.g.
if (Some conditions are true) then
Result := True
else
Result := False;
Another way, which is slightly inefficient but covers all bases, is to assign a predefined value to Result
as the first statement in the function and then assign another value to Result
later on in the function's code if some condition(s) applies.
Btw, because Tschool.Accepted
is a Boolean function, you can avoid writing an if ... else ...
by using a single assignment statement like this
function Tschool.Accepted : Boolean;
begin
Result := (fdeposit) and (fAge >= 4) and (fAge <= 6);
end;
because what's on the righthand side of the assignment is an expression of Boolean type.
In Delphi, there are often situations where execution of some code doesn't result in a useful (or interesting) value. Those are written as procedure
s rather than function
s. So, one answer to your q is that if a method of an object can usefully return a value, write it as a function
, otherwise write it as a procedure
and if you write it as a function
, make sure that it returns a value for any execution path through it.