Programming with Castalia : Refactoring : Extract Method
Previous  Top  Next

A fragment of code should be grouped together

Turn the fragment into a method with an explaining name.

procedure TForm4.Button1Click(Sender: TObject);  
var  
  Average: Double;  
  Sum: Integer;  
  I: Integer;  
begin  
  Sum := 0;  
  for I := 0 to Memo1.Lines.Count - 1 do  
  begin  
    Sum := Sum + StrToInt(Memo1.Lines[I]);  
  end;  
  Average := Sum / Memo1.Lines.Count;  
  Edit1.Text := FloatToStr(Average);  
end;  
 
downarrow  
function TForm4.CalculateSum: Integer;  
var  
  I: Integer;  
begin  
  Result := 0;  
  for I := 0 to Memo1.Lines.Count - 1 do  
  begin  
    Result := Result + StrToInt(Memo1.Lines[I]);  
  end;  
end;  
 
procedure TForm4.Button1Click(Sender: TObject);  
var  
  Average: Double;  
  Sum: Integer;  
  I: Integer;  
begin  
  Sum := CalculateSum;  
  Average := Sum / Memo1.Lines.Count;  
  Edit1.Text := FloatToStr(Average);  
end;  

Extract Method should be used when a method performs more than one complete function. The functions should separated out into distinct methods.

To use Extract Method, highlight the code that should be in its own method and select Extract Method from Castalia's refactoring menu. Castalia will create the new method, replacing the existing code with a call to the new method. Castalia will also decide whether the extracted method should be a
procedure or function, and create the code appropriately.

Castalia will then activate the multi-cursor, allowing you to select an appropriate name for the new method.

To finish, press Enter.

See also: Refactoring Overview, Rename Method Refactoring