Why create multiple extensions?


#1

This chapter has us creating three separate extensions on the Exercise protocol:

    extension Exercise {
    var caloriesBurnedPerMinute: Double {
        return caloriesBurned / minutes
    }
}
    extension Exercise {
    var description: String {
        return "Exercise(\(name), burned \(caloriesBurned) calories
                in \(minutes) minutes)"
    }
}
    extension Exercise {
    var title: String {
        return "\(name) - \(minutes) minutes"
    }
}

This seems strange to me. Why would you create three separate extensions instead of just one? I tried combining the behavior of these three extensions into one, as follows, and it worked just fine:

    extension Exercise {
    var description: String {
        return "Exercise(\(name), burned \(caloriesBurned) calories in \(minutes) minutes)"
    }
    var caloriesBurnedPerMinute: Double {
        return caloriesBurned / minutes
    }
    var title: String {
        return "\(name) - \(minutes) minutes"
    }
}

So what is the point of making three extensions in this situation rather than just one? It seems much simpler and concise to use just a single extension.


#2

The advantage is that you can add an extension to any file you like, and that you can even make it private so that it is not visible from other files.

You are not forced to modify an existing declaration, which is good for code maintenance and version control.


#3

Ah, that makes sense. I guess you would use multiple extensions if that works best for your project. The book wasn’t clear on that so it kind of left me scratching my head. Thanks for clearing that up!