Mega Code Archive

 
Categories / Delphi / Examples
 

Validate an object

Title: Validate an object Question: 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; A second example checks a name convention concerning a dBname and returns the altered name: function getPascalName(const aPrefix, aDBName: string): string; var i: integer; begin result:= aDBName; if result = '' then exit; try for i:= length(result) downTo 1 do if NOT (result[i] in ['0'..'9','a'..'z','A'..'Z','_']) then if result[i] in [#32, '$', '~'] then result[i]:= '_'; else delete(result, i, 1); result:= aPrefix + result; //check the result if (length(result) = 0) OR (result[1] in ['0'..'9']) then result:= '_' + result; except exit; end; end; You can call it then with an assert or an design by contract test, 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. So far there is Unit Testing a free and open source technology. It is a non intrusive technique for creating tests to verify that a class or an object behaves as expected. Write tests that check for expected failures or let the tests build by DUnit: Check CheckEquals CheckNotEquals CheckNotNull CheckNull CheckSame CheckException CheckInherits CheckIs Download DUnit from http://dunit.sourceforge.net/ Install DUnit into your source directory tree. It's better to install it into a directory tree where you store your sources not in a bin or program dir. I set up a Delphi environment variable called DUNIT that points that the DUnit src directory. In my case: d:\delphi\src\srcpas\dunit\src.