Properly separating concerns

Before you can improve your project structure with value types and protocols, it's a good idea to improve upon your structure in general. We haven't really thought about the reuse possibilities of certain aspects of the Hello-Contacts app, which results in code that's harder to maintain in the long run. This is especially true for larger projects that are built over an extended period of time.

If you take a look at the source code for this project in the book's code bundle, you'll find that the project was slightly modified. First, all the project files were put together in sensible groups. Doing so makes it easier for you to navigate your project's files, and it creates a natural place for certain files, as shown in the following screenshot:

The structure applied in this project is merely a suggestion; if you feel that a different structure would suit you better, go ahead and make the change. The most important part is that you've thought about your project structure and set it up in a way that makes sense to you and helps you navigate your project.

With this improved folder structure, you may notice that there's a natural separation between certain files. Some files help with transitions, a model file, several view controllers and more. By separating files into groups, you've given yourself an overview of the file types in your project, and each file belongs to a certain group that describes its place in your app. This makes it easier for other developers (and yourself) to browse the code in your project. Now that your project's file structure is solid, let's refactor some code.

The file we will refactor first is ViewController.swift. This file contains the code for the contacts overview screen. Currently, this view controller fetches contacts, acts as a delegate and data source for the collection view, and takes care of the animations that play when a user taps on a cell.

You may consider this to be okay. Ideally, any given class shouldn't be responsible for that many things at once. What if you need to create a second kind of overview page; how can you reuse the code that fetches contacts? What if you want to add the bouncing cell image animation to another image? These are two scenarios that are pretty likely to happen at some point in the future. Let's extract the contact-fetching code and the animation code and place them in their own structs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset