Home > Refactorings > Promoting locals and constant value expressions into parameters

Promoting locals and constant value expressions into parameters

July 31st, 2012

There are times when you realize that a local variable or a field reference within a method would be more useful if it was a parameter. Having a new parameter on a method will increase its flexibility for consumers. To convert the local variable, you should remove its declaration from the body of the method, add it as a parameter and replace all occurrences of a local to a new parameter. The same steps must be performed in the case of field references. Furthermore, all method references in the entire solution should be updated to pass a new value as an argument to a method with a new signature.

With the help of the Promote to Parameter refactoring, you can promote local variables, field references and any primitive values into parameters and make the required updates to the code automatically.

Choose a local variable, a field reference or a constant value and apply the refactoring to promote it into a parameter:

A field reference:

CodeRush Promote to Parameter field reference

A local variable:

CodeRush Promote to Parameter local variable

A constant value expression:

CodeRush Promote to Parameter primitive expression

In every case, a new parameter is added and all calls to the method are updated as required. You can immediately rename a new parameter according to your preference.

A second version of the refactoring called Promote to Parameter (optional) behaves in absolutely the same manner as its original version. The difference between two refactorings is that the latter creates an optional parameter instead of the usual parameter:

CodeRush Promote to Parameter (optional) preview

Optional parameters provide default values within the member’s signature. So, if an argument is omitted from a call to that method, the default value will be used instead:

CodeRush Promote to Parameter (optional) result

If we compare the Promote to Parameter refactoring to the Promote Local Variable to Parameter refactoring built-in to Visual Studio (VS refactoring), we see the following advantages of the refactoring shipped in CodeRush:

  • The VS refactoring does not allow you to create optional parameters
  • The VS refactoring can not be applied on the field reference within a method body
  • The VS refactoring can not be applied on constant value expressions within a method body.
—–
Products: CodeRush Pro
Versions: 12.1 and up
VS IDEs: 2008 and up
Updated: Jul/31/2012
ID: R061

Similar Posts: