Refactoring

One of the core elements of clean code is having code that is consistent with identifiers. Head to the AppDelegate. Take a look at this code from the tip from last week.

I have a few problems with it. I’m not being very consistent in some of those identifiers such as the HueColorTVC and ColorTableViewController. However, these identifiers are all over my code. There’s a great way to get consistency using refactoring. 

Select the HueColorTVC, then right click.

Click refactor… and then rename.

Xcode shows you all occurrences of this identifier, which in this case is only in the app delegate.

Change to hueColorTableViewController. All the occurrences change at once. 

Select and then right-click the ColorTableViewController, and once again hit refactor.

Both cases of the class identifier, when it is instantiated in teh App delegate and the definition in HueColorTVC.swift are highlighted. Change to HueColorTableViewController

Let’s do this one more time. I’m going to change the navigationVC

to masterNavigationVC

Now I’d like my file name to match too. One way to change it is in attributes. Select HueColorTVC.swift.

Open the attributes panel. Change the name to HueColorTableViewController.swift

and the file name changes.


One caution about all this renaming. Comments don’t refactor easily. You’ll see that at the top of the code.  Select and refactor that. You can’t. Once you refactor, you might want to also search to find anything you didn’t get in your refactoring. You can replace all these cases by selecting replace, and adding the replacement in the text box. 

Refactoring is a very useful and simple tool to get your code a lot more consistent in identifiers. 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: