In the intro, we talked about the problem we want to tackle, which is to refactor DragTile to be more flexible. If you haven’t read it yet, you might want to check it out.
Back? Ok. Now, let’s look at some code.
Step 0 – the starting point
Step 1 – pull up the FlexibleContainer superclass
Even though we said we were going to use composition instead of inheritance to separate these classes, we do this as a first step because it is easier than pulling out a helper class.
Tip 3: Always refactor in small steps that leave the external behavior unchanged
The basic procedure is to create a superclass (which I called “FlexibleContainer”) and to walk through the DragTile code method by method and property by property to move things to the superclass if it seems appropriate.
I started by moving all of the local variables that seemed “general” to the superclass. This included the _items array, the renderers array, and so forth. The variables that seemed specific to the Tile layout were left in the DragTile class.
Because most of these variables were private, moving them to the superclass caused a lot of compile errors, most of which I fixed by moving the appropriate methods to the superclass.
In one case (dragTargetIndex) I needed to create a protected accessor so that the subclass could get at this information. If you want to be a stickler about it, making a private member protected requires some thought. Is this the right way for a subclass to get information from its superclass? In this case, it’s probably not the right thing. The “right” thing is probably to pass the drag information as a parameter during the drag operation. This brings us to the next tip:
Tip 4: When refactoring, don’t try to make it “perfect”. Just strive to incrementally improve the code each time you touch it.
Creating a protected accessor here was the quickest way to separate these two classes without overcomplicating the design. We can come back and fix this later after the dust has settled.
At this point, the FlexibleContainer class and the DragTile class have been completely separated. The outlines look like this.
After the first refactoring, the new API looks like this. Remember that our goal here is to put all the logic that is specific to a specific layout (Tile) into one class, leaving as much of the general code in the superclass as possible. The DragTile class should be as small as possible (but no smaller!) :
Source code for step 1 can be found here.