I’ve spent quite a bit of time this week tidying up the course exercises and solutions for Learning Tree’s Building iPhone® and iPad® Applications: Extended Features course. There were a few bug fixes based on instructor feedback but it was mostly a process of upgrading to modern Objective-C and refactoring the existing code to make it more readable and easier to follow as students work through exercises.
The conversion to modern Objective-C that I referred to in my last post was very useful, but I also made use of Xcode’s other refactoring tools. These are worth exploring because they do make tidying up existing projects less of a chore. You’ll find all the refactoring tools on the Edit | Refactor menu.
This is the one I use a lot. I like code that reads well, with meaningful class, variable and method names. Objective-C is particularly good in this respect because of the way it handles method arguments, something I covered in a previous post: Making Friends with Objective-C.
Good names don’t always flow from my keyboard in the heat of development and I like to go back and improve things every so often. The rename refactoring will take any highlighted class name, variable name or method name and intelligently change it throughout the project. More than a simple search and replace, this is an intelligent refactoring that ensures only the required replacements are made and gives the option of renaming class files where necessary.
Extract is another useful one. Select a few lines of code and it will extract those lines into a method. This is a good one as a project expands and you find yourself tempted by copy and paste to re-use a few lines of code. The extract refactoring is reasonably intelligent and will create a method with all the arguments the method needs and make the appropriate call to the method in place of the code you selected.
Create Superclass, Move Up and Move Down
These three go together. The create superclass refactoring will make an new parent class for a given class. You can then select methods and instance variables to be moved up into the parent class definition. If you change your mind about moving a symbol up a level, you can simply move it back down again with the move down refactoring.
In a lot of the iOS code I see, inheritance is really underused and these tools mean there is no excuse for not improving that.
I don’t think I’ve ever used this one. The idea here is that you select an instance variable and create accessor (getter) and mutator (setter) methods. Given that this produces what is in effect a property and the property declaration and synthesis now only requires a
@property declaration, I don’t find it that useful.
Next time you are at the stage where your project needs some cleaning up, try these refactoring tools. They’ll help you get back to the creative process more quickly.