Sunday, September 26, 2010

How to create a new class

When refactoring small-scale (this typically means creating 1 new class), we have the following 3 main actors:

U: The user class (or classes)
N: The new class, which will contain some of the original class's functionality, and relieve it from bloat
O: The original class (out of which we want to extract some functionality and put it into N).

So here are the steps we want to take in order to get the process under way systematically:

  1. Identify the original class O.
  2. Decide which of the O's functionality will be moved into N
    • Often there will also need to be a reference from N to O, as we still need the information from O to execute some of the logic. This dependency can be removed at a later point, but in early stages of refactoring, it's almost always useful to have.
    • For simplicity consider making N a friend of O. This may help get things working initially. This may be good to remove later, when the two classes have become sufficiently decoupled.
  3. Decide what data members N will have, and what is its constructor signature (perhaps it gets some info from O)
    • Create the new function declarations in N that correspond to O's functionality (possibly with different signatures). So O.foo() and O.bar(), become N.fu(), and N.baar()
    • Move over the definition of each function from O to N
    • Change the definition with respect to N, to fit the new function signatures, and the new data members of N
    • Find places where the code we used was called in the U.
    • Replace the calls to members of O with calls to members of N.
    • Remove the functionality from O
    • If you resorted to the "friends" solution, consider if N still needs to be a friend of O. 
    • If you included O from N, consider if this dependency is still needed
    I realize that this list is quite fuzzy, with some of the steps being far from mechanical. There's a bit of an art to the process of creating a new class, and I'm hoping to pin the process down further in my future posts. 

    No comments:

    Post a Comment