1

I wrote this redundant code consisting of 30 lines:

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;

I manually refactored the code by extracting it to a small method by applying just logic:

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;

Then I used the method by these 4 lines of code (Savings of 26 lines compared to the previous redundant code):

if Button = TMouseButton.mbLeft then
  SetPanelColors(pnlStartColor, pnlEndColor, ThisColor)
else
  SetPanelColors(pnlEndColor, pnlStartColor, ThisColor);

How could such a refactoring of redundant code be automated? Are there any libraries or general resources for such a purpose?

4
  • Sometimes the "Extract method" option works, but typically you do this manually using the clipboard and class completion. Commented Nov 27, 2021 at 15:46
  • By chance, I came across the website of Refactor! Pro 3.0: devexpress.com/aboutus/newsreviews/refactor30.xml It would be fantastic having such a tool for Delphi! Commented Nov 27, 2021 at 15:49
  • Have a look at MMX Code Explorer plugin Commented Nov 28, 2021 at 9:15
  • Regarding the refactoring ... 1) There is still a good deal of redundancy in the procedure code. It can be reduced to : delphi procedure TForm1.SetPanelColors(Panel1, Panel2: TPanel; const aColor: TColor); begin if Panel2.ShowCaption then Panel2.Color := aColor; Panel2.ShowCaption := False; Panel1.ShowCaption := False; Panel1.Color := aColor; end; 2) I think the blind 'if else' in the last section should probably be replaced with a case statement on mbLeft and mbRight. Commented Aug 22, 2023 at 18:10

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.