今天做了一個(gè)小軟件,總結(jié)了一些經(jīng)驗(yàn)與大家共享。源代碼過一段時(shí)間我可能公布,希望與大家共同學(xué)習(xí)。
1、用sender的方式增強(qiáng)代碼的健壯性
PRocedure TMainfrm.CBAutoRunClick(Sender: TObject);
Const
SIGNINREGISTRY = 'WebSuction';
begin
if (Sender as TCheckBox).Checked then //用sender as...的方式可適應(yīng)
//性更強(qiáng)
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、不要出現(xiàn)魔法數(shù)
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、錯(cuò)落有致
procedure TMainfrm.WMHotKey(var Msg : TWMHotKey);
begin
if (Msg.HotKey = FHotKeyId) and (ClipBoard.HasFormat(CF_TEXT)) and
(not ClipBoard.HasFormat(CF_PICTURE)) then//不要超過一行能容納的字?jǐn)?shù)
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 用面向?qū)ο蟮姆椒ㄊ褂胐elphi。
這是我做這個(gè)軟件最大的體會(huì),以前我用面向過程的方法做過這個(gè)軟件,代碼思路特別亂,現(xiàn)在用了OO的方法就是不一樣
這個(gè)一句兩句可說不清楚,公布源碼后大家自己看吧
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注