Tuesday, February 16, 2016

Refactoring - exact utility method

When working on a project, especially when multiple developers are involved, the same functionality might be duplicated in different classes.

This, is course, is not only a waste of bytes but it increases the chance of bugs and makes maintenance difficult.

The code needs to be merged and moved in the class that makes more sense or into a new class.

Consider the following two classes:

class User {
    func trim(s:String) -> String {
        return s.stringByTrimmingCharactersInSet(
            NSCharacterSet.whitespaceAndNewlineCharacterSet()
        )
    }
    //more functionality
}

class Product {
    func trimString(s:String) -> String {
        return s.stringByTrimmingCharactersInSet(
            NSCharacterSet.whitespaceAndNewlineCharacterSet()
        )
    }
    //more functionality
}


We notice that trim and trimString have the same functionality.

The first solution would be to create an utility class to include both functionality:

class Util {
    class func trim(s:String) -> String {
        return s.stringByTrimmingCharactersInSet(
            NSCharacterSet.whitespaceAndNewlineCharacterSet()
        )
    }
}

We defined it as a class function so we can simply call the function like follows:

Util.trim(" qqq \n\t")

A better solution is to create an extension to the class String:

extension String {
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(
            NSCharacterSet.whitespaceAndNewlineCharacterSet()
        )
    }
}

In this case we can simply call the trim functionality:

" qqq \n\t".trim()

No comments:

Post a Comment

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