Best practice to prevent Bugs and Exceptions during coding in Delphi

To develop a good application it needs to be bug free and as a good developer we need to code in best to prevent Bugs and Exception that may be raise during application run. So here in this blog I have pointed some steps for best coding practice.

1.  Hints and Warnings
Solve all hints and warnings that shows during compile and build of an application in Delphi IDE. The warnings marked by Delphi can really cause some errors in runtime.

2. Items of lists
Never access items of a list without being sure that the item really exists in that list or not freed.
Example
if objText.Count > 10 then
strText := objText.Strings[10];

3. Pointers to objects
Use the Assign function to check if an object is still assigned to a pointer. When freeing the object, also make sure the pointer is set to nil.
Example
if Assigned(objText) then
intCount := objText.Count;
FreeAndNil(objText);

4. Using of Try - Finally
Always use a try-finally structure where you have to be sure some actions are executed to finish what has been started.
Example
a. DisableControls & EnableControls : Use the DisableControls of a Dataset to prevent flickering and to make dataset actions a lot faster.
try
dataset1.DisableControls;
finally
dataset1.EnableControls;
end;

b. Create & Free of any object and components
try
objStrings := TStringList.Create;

finally
objStrings.Free;
end;

C. Screen.Cursor:=crHourglass & Screen.Cursor:=crDefault
try
Screen.Cursor := crHourGlass;

finally
Screen.Cursor := crDefault;
end;

d. GetBookmark & FreeBookmark
try
ptrBookmark := GetBookmark;

GotoBookmark(ptrBookmark);
finally
FreeBookmark(ptrBookmark);

end;

5. Using of Try-Except
Make sure the option Stop on Delphi exceptions in the Language exceptions of the Debugger options is checked. Use try-except structure for all actions which can go wrong. Make sure the exception is only called for exceptional cases. An exception is very slow so it is a lot better to add some if conditions if the exception does occur frequently.
Example
try
//do somthing //
except
showmessage('Error');
end;

or 

try
//do somthing //
except on E:Exception do
showmessage('Error ='+E.message);

end;

6. Use the StrToIntDef and StrToDateDef 
StrToIntDef and StrToDateDef functions to give a default in case the conversion goes wrong.
Example
int1  := StrToIntDef(snum1, 0); 
//if not able to convert snum1 to integer instead of raise exception it will return 0 as default value
Date1 := StrToDateDef(sdate1, Now); 
//if not able to convert sdate1 to date instead of raise exception it will return Now the system date as default value

Comments

Popular posts from this blog

MS Excel Automation in Delphi

ShellExecute in Delphi

Drawing Shapes in Delphi