wiki:RefactoringSteps/IntroduceRecord

Version 1 (modified by manualwiki, 13 years ago) (diff)

--

Introduce record

Given a tuple skeleton, this transformation converts it to a record expression and inserts compensating record expressions or record update expression at the needed places.

Introduce record cart with fields re and im:

-export([mul/2]).

mul({Re1,Im1},{Re2,Im2})->
   {Re1*Re2-Im1*Im2,
   Re1*Im2+Im1*Re2}.

Result:

-export([mul/2]).

-record(cart, {re, im}).

mul(#cart{re=Re1, im=Im1},
    #cart{re=Re2, im=Im2})->
   #cart{re=Re1*Re2-Im1*Im2,
   im=Re1*Im2+Im1*Re2}.

Side conditions

  • The name of the record we introduce should not conflict with another record. Furthermore, the name and field names should be a legal record name. If the name or the field name is not legal, the transformation starts an interaction to ask for a new name.
  • The starting and ending positions should delimit a tuple skeleton.
  • The transformed tuple cannot be embedded in a list comprehension, list or another tuple.
  • The given field names number should match the number of the tuple’s elements.
  • The selected tuple cannot be a parameter of a function expression.
  • If the selected tuple is a function parameter, there must not be an implicit reference to the function.

Transformation steps and compensations

  1. The refactoring finds every tuple in the function pattern, which has the same type.
  1. The transformation checks every function clause to find those, which parameter contains at least one same typed tuple.
  1. The refactoring collects every function calls, which calls the collected function clause.
  1. The refactoring finds all function calls in the collected function clauses, where the parameter contains at least one same typed tuple.
  1. The transformation collects the return parameter, if it is a same typed tuple.
  1. The refactoring finds every function calls in the collected function clauses, which parameter contains at least one same typed tuple. The transformation finds that function and the collection starts again from the first step.
  1. If the record didn’t exist before, its definition is constructed.
  1. The collected tuples in the function patterns are replaced to record expressions. If a function clause contains function calls, the affected record gets bound with a variable name.
  1. The return value is transformed to a record expression, if it was collected.
  1. The unused variable (in the record expression) are eliminated.
  1. Those function calls parameters, which calls a collected function, are transformed to record expression.
  1. If a collected function’s return parameter is a same typed tuple, and the calling place is match expression, the left side is transformed to a record expression too.