2005. július 13., szerda

Validate an object


Problem/Question/Abstract:

How do you check if an object fits your condition and that of the compiler ?

Answer:

From time to time you want to be sure, if an object fits your conditions like naming conventions, robustness or you want the compiler find  no further errors. The  function checkOBJ determines whether a passed object, with a boolean returned from the function, represents an error condition.

function TTrans.checkOBJ(aObject: TObject): boolean;
var
  str: string;
  i: integer;
begin
  result := false;
  if aObject = nil then
    exit;
  try
    str := ansiUppercase(aObject.classname);
    if str = '' then
      exit;
    for i := 1 to length(str) do
      if not (str[i] in ['0'..'9', 'A'..'Z', '_']) then
        exit;
    aObject.classType;
    if aObject.InstanceSize < 1 then
      exit;
    aObject.ClassnameIs('TObject');
    result := aObject.ClassNameIs(aObject.Classname);
  except
    exit;
  end;
end;

You can call it then with an assert, so you get during the development a bit of quality assurance ;).

accObj := TAccount.createAccount(FCustNo, std_account);
assert(aTrans.checkOBJ(accObj), 'bad condition with OBJ'); //trans

Use Assert as a debugging check to test that conditions assumed to be true are never violated. Assert provides an opportunity to intercept an unexpected condition and halt a program rather than allow execution to continue under unanticipated conditions.

Nincsenek megjegyzések:

Megjegyzés küldése