wiki:RefactoringSteps/DuplicateCodeElimination

Duplicate Code Elimination

The “ Duplicate Code Elimination” transformation eliminates a duplicate code group. This transformation needs a duplicate code group found with the filtered_suffix_tree algorithm, with max_invalid_seq length parameter set to 0. More information about duplicate code analysis can be found at here. If the members of the group are found in different modules the transformation asks the user to enter a module name where the extracted function should be placed, and exported. Every occurrence of the group will be replaced with a function call to the extracted function. The transformation asks the user to enter the extracted function's name.

Eliminate a clone gorup:

-module(clone).

-export([f/0, g/0]).

f() ->
   A = 5,
   B = A + A,
   case A of
      5 -> io:format("~p~n",[A]);
      _ -> io:format("Function f")
   end.

g() ->
   C = 6,
   case C of
      6 -> io:format("~p~n",[C]);
      _ -> io:format("Function g")
   end.

Result:

-module(clone).

-export([f/0, g/0]).

f() ->
   A = 5,
   B = A + A,
   new_fun(A, 5, "Function f").

g() ->
   C = 6,
   new_fun(C, 6, "Function g").

new_fun(NewVar1, NewVar2, NewVar3) ->
   case NewVar1 of
      NewVar2 -> io:format("~p~n",[NewVar1]);
      _       -> io:format(NewVar3)
   end.

Side conditions

  • The extracted function name should not conflict with an already used function name.

Transformation steps and compensations

  1. Given the clone name, clone group, the transformation analyses the group and finds the variables which will be extracted.
  2. Calls the extract_funcion transformation to create a new function, and replaces the group members to a call to the extracted function.
Last modified 9 years ago Last modified on Mar 11, 2015, 10:54:09 AM