Magic pushbutton

From Wikipedia, the free encyclopedia

This article or section may contain original research or unverified claims.
Please help Wikipedia by adding references. See the talk page for details.

The magic pushbutton anti-pattern is very common in graphical programming environments. In this scenario, the programmer draws the user interface first and then writes the business logic in the automatically created methods.

Problems with this anti-pattern are:

  • The code behind the Pushbuttons grows unmanageably
  • Changing the user interface (or adding an alternate interface) is difficult
  • Testing the code is difficult

[edit] Bad Example (Borland Delphi)

procedure TForm1.Button1Click(Sender: TObject);
var
  reg:TRegistry;
begin
  reg:=TRegistry.Create;
  try
    reg.RootKey:=HKey_Current_User;
    if reg.OpenKey('\Software\MyCompany',true) then
    begin
      reg.WriteString('Filename',edit1.text);
    end;
  finally
    reg.Free;
  end;
end;

[edit] Good Example (Borland Delphi)

A better way to do this is to refactor the business logic (in this example storing the filename to the registry) into a separate class.

type
 TPreferences = class
 private
   FFilename: string;
   procedure SetFilename(const Value: string);
 public
   property Filename:string read FFilename write SetFilename;
   procedure Load;
   procedure Save;
 end;

and call this class Save method from the Click handler:

procedure TForm1.Button1Click(Sender: TObject);
begin
  Preferences.Save;
end;
procedure TForm1.Edit1Change(Sender: TObject);
begin
  Preferences.Filename:=edit1.text;
end;

[edit] References

    In other languages