Back to TTCN-3 Refactoring Catalog
Extract Template
A template with the same values inlined more than once should be extracted into a template on its own to support code reuse and maintenance.
Motivation
Inlined templates of simple structured types are nice as they can improve readability. In fact, the Inline Template refactoring even recommends the use of inlined templates when a simple template declaration is referenced only once. However, when a template with the same values is inlined more than once, there are reduced possibilities for code reuse due to code duplication and the maintainability is bad. Hence, the duplicate inlined templates (sources) should be extracted into a single target template declaration. The duplicate inlined source templates are replaced with a reference to the target template declaration and the code duplication is thus removed.
Mechanics
- Identify duplicate inlined source templates having the same value list notation.
- Create a new target template declaration containing the values of the duplicate inlined source templates. Give it a meaningful name describing the content of the values.
- Compile.
- Replace the duplicate inlined source templates with a reference to the new target template declaration. If the template declaration is located in a different module than the inlined source template, an import statement must be added or adjusted to include the target template declaration.
- Compile and validate.
Example
The example illustrates the Extract Template refactoring as a reversed Inline Template refactoring. In the following listing, two send statements use inlined source templates with the exactly the same values.
// ...
type record MyMessageType {
integer field1 optional,
charstring field2,
boolean field3
}
// ...
testcase tc_exampleTestCase() runs on ExampleComponent {
// ...
pt.send( MyMessageType:{omit, "My string", true} );
// ...
pt.send( MyMessageType:{omit, "My string", true} );
}
After applying the Extract Template refactoring, this code duplication is removed. A new target template declaration a_myMessageTemplate is created. The duplicate inlined source templates are replaced with a reference to the target template declaration. As the duplicate inlined source templates are all within the same module, the import statement is not changed.
// ...
type record MyMessageType {
integer field1 optional,
charstring field2,
boolean field3
}
template MyMessageType a_myMessageTemplate := {
field1 := omit,
field2 := "My string",
field3 := true
}
// ...
testcase tc_exampleTestCase() runs on ExampleComponent {
// ...
pt.send( a_myMessageTemplate );
// ...
pt.send( a_myMessageTemplate );
}
