Extract Implementation From Header
This is a C++ refactoring:
You have a class that is implemented completely within its own header and you want to hide its implementation from its clients.
Move all the method bodies out of the header file and into a new implementation file. Move as many #includes out of the header file into the implementation file as possible, replacing them in the header with forward declarations.
[ToDo: provide a summary of the mechanics]
- Motivation
- You probably want to do this to reduce dependencies either to decrease compile times or to remove a circular dependency.
- Mechanics
-
- Copy the entire contents of the .h file to a new .cpp file
- Continue editing the .cpp file
- Remove the IncludeGuard.
- #include the header as the first #include in the file (ensures standalone compilability of the file see: LargeScaleCppSoftwareDesign)
- Remove everything from the class definition except the definitions of the methods.
- Select all the method definitions and extend them one level (this should bring them flush with the left margin).
- Type the class name followed by double colons immediately preceding the first method name.
- Copy what you just typed to the clip board.
- Paste it to the beginning of all the method definitions so that they become correctly scoped.
- Edit the .h file
- Replace all the method bodies in the .h file from the close parenthesis of the declaration to the closing curly brace of the definition with a semicolon.
- Visit each #include in the header. For each one:
- If the #included class is ever used by value (declared as a member or passed by value to a method) skip to the next #include
- If the #included class is used only by reference replace the #include with a forward reference.
- Gather all the forward references together just after the #includes.
- Recompile and retest.
[ToDo: actually try doing this refactoring using these instructions to ensure that I haven't left anything out]
[ToDo: include an example]
--PhilGoodwin
CategoryRefactoring CategoryCpp
EditText of this page (last edited November 14, 2000)
FindPage by browsing or searching
This page mirrored in WikiPagesAboutRefactoring as of July 17, 2004