今天做了一个小软件,总结了一些经验与大家共享
1、用sender的方式增强代码的健壮性
procedure TMainfrm.CBAutoRunClick(Sender: TObject);
Const
SIGNINREGISTRY = ''WebSuction'';
begin
if (Sender as TCheckBox).Checked then //用sender as...的方式可适应
//性更强
AddToAutoRun(Application.ExeName,SIGNINREGISTRY)
else DelAutoRun(SIGNINREGISTRY);
end;
即使Checkbox1改了名字也不怕
又如:
procedure TMainfrm.N1Click(Sender: TObject);
begin
if (Sender as TMenuItem).Caption = ''暂停(&S)'' then
begin
(Sender as TMenuItem).Caption := ''开始(&R)'';
FWebPageSaver.Pause;
end
else
begin
(Sender as TMenuItem).Caption := ''暂停(&S)'';
FWebPageSaver.ReStart;
end;
end;
2、不要出现魔法数
  function ExtractFileNameFromText( AText : string): string;
  Const
  MAXLENGTH = 250;//Max length of filename
  var
  LTextLength, I : integer;
  LString : string;
  begin
  LString := AText;
  LTextLength := Length(LString);
  for I := 0 to LTextLength-1 do
  begin
  if IsInvalidChar(LString[I]) then
  LString[I] := ''n'';//Change the Invalid char with ''n''
  end;
//在返回语句与前面的代码之间用空行隔开
  result := LeftStr(LString,MAXLENGTH);//让人一看就知道MAXLENGTH是什么意思,比直接写250好
  end;
3、错落有致
  procedure TMainfrm.WMHotKey(var Msg : TWMHotKey);
  begin
  if (Msg.HotKey = FHotKeyId) and (ClipBoard.HasFormat(CF_TEXT)) and
  (not ClipBoard.HasFormat(CF_PICTURE)) then//不要超过一行能容纳的字数
  FWebPageSaver.NewTextFile(ClipBoard.AsText);
  end;
4、不要直接使用Tform2单元的全局Form2变量,那样就破坏了封装性
  procedure TMainfrm.SBNextClick(Sender: TObject);
  var
  LSelectedIndex : integer;
  FormDisplay : Tform2;
  begin
  LSelectedIndex := LBWebPage.ItemIndex;
  if LSelectedIndex <> -1 then
  begin
  FormDisplay := Tform2.Create(self);
  FormDisplay.SetContent(FWebCracker.GetWebText(LSelectedIndex));
  FormDisplay.Show;
  end;
  end;
  在TForm2中定义 SetContent方法
  procedure TWebCrackfrm.SetContent(AText:string);
  begin
  Memo.Clear;
  Memo.Lines.Add(AText);
  end;
5 用面向对象的方法使用delphi。
  这是我做这个软件最大的体会,以前我用面向过程的方法做过这个软件,代码思路特别乱,现在用了OO的方法就是不一样
  这个一句两句可说不清楚,公布源码后大家自己看吧
下载地址:
  http://lincosoft.go.nease.net/
