Wednesday, February 3, 2016

Refactoring - Replace type code with enumeration

Karate is a Japanese style of martial arts that rewards its participant attaining a certain level of sport mastery with color belts.

Let's have a class for a Karateka, that is a Karate practitioner.

let kWhiteBelt = 0, kYellowBelt = 1, kOrangeBelt = 3 
let kGreenBelt = 4, kBlueBelt = 5, kBrownBelt = 6, kBlackBelt = 6

class Karateka {
    var name = ""
    var belt = kWhiteBelt
    
    func isBeginner () -> Bool {
        return belt == kWhiteBelt
    }
    
    func isMaster () -> Bool {
        return belt == kBlackBelt
    }
}

The code works fine but it is not an elegant one.


And it is error prone. Consider the following code:

var belt = kYellowBelt
++belt

What will be the value of the belt? kOrangeBelt? Look again. The value of kYellowBelt is 1 and there is no value for 2, the current value of the belt.

Here is a more elegant solution:

enum Belt {
    case White, Yellow, Orange, Green, Blue, Brown, Black
}

class Karateka {
    var name = ""
    var belt = Belt.White
    
    func isBeginner () -> Bool {
        return belt == .White
    }
    
    func isMaster () -> Bool {
        return belt == .Black
    }
}

Trying now to use ++ operator on a Belt object will result in a compilation error

No comments:

Post a Comment

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