我编写了这个由30行组成的冗余代码:
if Button = TMouseButton.mbLeft then
begin
if pnlEndColor.ShowCaption then
begin
pnlStartColor.ShowCaption := False;
pnlEndColor.ShowCaption := False;
pnlStartColor.Color := ThisColor;
pnlEndColor.Color := ThisColor;
end
else
begin
pnlStartColor.ShowCaption := False;
pnlStartColor.Color := ThisColor;
end;
end
else if Button = TMouseButton.mbRight then
begin
if pnlStartColor.ShowCaption then
begin
pnlStartColor.ShowCaption := False;
pnlEndColor.ShowCaption := False;
pnlStartColor.Color := ThisColor;
pnlEndColor.Color := ThisColor;
end
else
begin
pnlEndColor.ShowCaption := False;
pnlEndColor.Color := ThisColor;
end;
end;
我通过仅应用逻辑将代码提取到一个小方法来手动重构代码:
procedure TForm1.SetPanelColors(Panel1, Panel2: TPanel; const aColor: TColor);
begin
if Panel2.ShowCaption then
begin
Panel1.ShowCaption := False;
Panel2.ShowCaption := False;
Panel1.Color := aColor;
Panel2.Color := aColor;
end
else
begin
Panel1.ShowCaption := False;
Panel1.Color := aColor;
end;
end;
然后我用这4行代码的方法(相比之前的冗余代码节省了26行):
if Button = TMouseButton.mbLeft then
SetPanelColors(pnlStartColor, pnlEndColor, ThisColor)
else
SetPanelColors(pnlEndColor, pnlStartColor, ThisColor);
这种冗余代码的重构如何自动化?是否有任何图书馆或通用资源用于此目的?