Free refactor tool in all versions of Visual Studio, totally cool
I have been using refactoring with C# for quite awhile, and realized that many readers may not have noticed that the refactoring tool is quite smart. In the following code, I noticed that the code starting with “String ViewportHeight” down to String BallX could be put in a method, but I was being lazy and not wanting to generate a parameter passing function. Turns out that refactor detects the parameters and puts them into the refactoring for you!
Start with this code in the draw method:
protected override void Draw(GameTime gameTime)
{
spriteBatch.Begin();
spriteBatch.Draw(t_ball, r_ball, Color.Red);
/*****************************************************
* Refactor Code starts here (start paste after
* the line of asteriks or stars)
* ***************************************************/
String ViewportHeight =
Convert.ToString(graphics.GraphicsDevice.Viewport.Bounds.Height);
String ViewportWidth =
Convert.ToString(graphics.GraphicsDevice.Viewport.Width);
String ViewportData =
"Height =" + ViewportHeight + " Width = " + ViewportWidth;
String BallY =
"Y= " + Convert.ToString(r_ball.Y);
String BallX =
"X= " + Convert.ToString(r_ball.X);
/*****************************************************
* Refactor code finishes here (End paste at the line
* above the line of asteriks or stars)
* **************************************************/
spriteBatch.DrawString(Font1, ViewportWidth, FontPosX, Color.Yellow);
spriteBatch.DrawString(Font1, BallY, FontPosY, Color.Black);
spriteBatch.End();
base.Draw(gameTime);
}
Right click on the commented code and select refactor-extract method, add a method name (that is: don’t use the default name)
The code changes into the following:
/*****************************************************
* Refactor Code starts here (start paste after
* the line of asteriks or stars)
* ***************************************************/
String ViewportWidth;
String BallY;
StringForData(out ViewportWidth, out BallY);
/*****************************************************
* Refactor code finishes here (End paste at the line
* above the line of asteriks or stars)
* **************************************************/
The following method was added by the refactoring:
private void StringForData(out String ViewportWidth, out String BallY) { String ViewportHeight = Convert.ToString(graphics.GraphicsDevice.Viewport.Bounds.Height); ViewportWidth = Convert.ToString(graphics.GraphicsDevice.Viewport.Width); String ViewportData = "Height =" + ViewportHeight + " Width = " + ViewportWidth; BallY = "Y= " + Convert.ToString(r_ball.Y); String BallX = "X= " + Convert.ToString(r_ball.X); }