Advanced ActionScript Refactoring – Step 1
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
The original files for my investigation can be downloaded from Ely’s site, or you can get my slightly munged version here.
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.