Monday, February 1, 2016

Refactoring: Change bidirectional association to unidirectional

In the previous post we analyzed how, sometime, adding another association between the objects can drastically improve performance and reduce the amount of code we need to write.

The situation can happen in reverse as well.

Consider the following example:


class Person {
    var name: String?
    var address: Address?
}

class Address {
    var streetName: String?
    //other properties

    var personArray = [Person]()
}

The structure of the classes is clear. For each person we are interested in the Address, among other information.

There can be the case where multiple people are living at the same location, so the Address class has an array of Person objects.

What if our program is never interested in who is living at a certain address? What if only the Person objects are of interest and now and then the address is retrieved for a certain person?

In this case, we can safely remove the double association, save some memory and simplify the code in the process:

class Address {
    var streetName: String?
    //other properties
    var personArray = [Person]()
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.