- Magic pushbutton
-
The magic pushbutton is a common anti-pattern in graphical programming environments.[1] In this scenario, the programmer draws the user interface first and then writes the business logic in the automatically created methods.
In event-driven programming, a few functions or "event handlers" are written by the programmer that respond to the user's actions. This technology means that instead of having to write the core functionality for each new program over and over again, a programmer can just add functionality to an application skeleton provided for them.
In the Magic Pushbutton, the only event handler that does any real work is the one that's called when the user clicks the return button. If the programmer does not deliberately organize the program's code in a better way, then it all accumulates in this one routine, which ends up as a huge, unmanageable blob of code.[2]
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
Example
The following is a typical example of a magic pushbutton in 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;
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;
References
- ^ http://www.scribd.com/doc/99553/AntiPattern-by-Indranil-Nandy-IIT-Kharagpur
- ^ Software project secrets: why software projects fail By George Stepanek
Categories:- Anti-patterns
- Computer science stubs
Wikimedia Foundation. 2010.