Friday, January 29, 2016

Refactoring - Introduce new method

Consider you have a function that perform an activity on an object a certain class in multiple places across the class and the project.

Sometimes, it makes sense to add that functionality directly to the class.

Swift makes this very simple using extensions. They allow to add new functionality to an existing class, structure or enumeration even if you do not have access to its code.

Let's take the following example:


class Activity {
    var durationInSeconds: Double = 0
   
    func durationAsMinutes() -> Double {
        return durationInSeconds/60
    }
    func durationAsHours() -> Double {
        return durationInSeconds/60/60
    }
    func durationAsDays() -> Double {
        return durationInSeconds/60/60/24
    }
}

The disadvantage of this code is that the functionality to convert seconds into minutes, hours and days is local to the Activity class. What if there is another class that needs the same methods? Will we replicate the code? What if there is another property in Activity (for example delayInSeconds) that needs the same functionality.

In our case, it makes sense to add this functionality directly to the type used, in this case Double.

We can create an extension in the following way:

extension Double {
    var minutes: Double {
        return self/60
    }
    var hours: Double {
        return self/60/60
    }
    var days: Double {
        return self/24/60/60
    }
}

Consider we have the following variable:

let duration:Double = 1200

We can convert it to minutes, hours and days, in the following way

duration.minutes
duration.hours
duration.days

Of course, this functionality is accessible to any other code from the current module.

No comments:

Post a Comment