Tuesday, January 26, 2016

Refactoring in Swift - Replace Array with an Object

This refactoring applies to the case when different kinds of information are stored in an array.

For example, we have an array storing the first name, the last name and the age as follows:



let database = ["John", "Williams", "30", "Robert", "Jones", "40", "Julia", "Adams", 21]

While this is okay for small programs, it becomes difficult to manage for bigger databases. What is the meaning of database[234] for example? It is a first name, a last name?

We can solve this problem by having a new class, for each group of information. For example:

class Person {
    var firstName, lastName, age: String
    
    init(firstName:String, lastName: String, age:String){
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    }
}

In this case our database becomes:

let database = [
    Person(firstName: "John", lastName: "Williams", age: "30"),
    Person(firstName: "Robert", lastName: "Jones", age: "40"),
    Person(firstName: "Julia", lastName: "Adams", age: "21") ]

We now know that all the array elements are of the Person type, so the confusion about what type is an element disappeared.

And of course, if a new type of data is added, the solution is simply just adding a new property to the class and changing the code populating the object.


No comments:

Post a Comment