Hello world!

let greeting = "Hello, world!"
println(greeting)

Not bad, but not exactly object oriented. Improve all the code!

class Greeting {
    func greet()->String {
        return "Hello, world!"
    }
}

let greeting = Greeting()
println(greeting.greet())

That’s better. That string is nagging me, though. It should be declared as a constant. Improve all the code!

final class Greeting {
    private struct Constants {
        private static let greet = "Hello, world!"
    }
    func greet()->String {
        return Constants.greet
    }
}

let greeting = Greeting()
println(greeting.greet())

That’s better. However, there is still something wrong. I don’t like how my code expects an instance of Greeting, what if I need a different implementation of the greet method?. Improve all the code!

protocol Greet {
    func greet()->String
}

final class Greeting: Greet {
    private struct Constants {
        private static let greet = "Hello, world!"
    }
    func greet()->String {
        return Constants.greet
    }
}

let greeting: Greet = Greeting()
println(greeting.greet())

But wait! Now there is a hardcoded dependency in there. I expect an abstraction, but create an instance of a specific class. This clearly calls for a factory. Improve all the code!

protocol Greet {
    func greet()->String
}

final class Greeting: Greet {
    private struct Constants {
        private static let greet = "Hello, world!"
    }
    func greet()->String {
        return Constants.greet
    }
}

final class GreetingFactory {
    class func greeting()->Greet
    {
        struct Static
        {
            static let greeting = Greeting()
        }
        return Static.greeting
    }
}

let greeting = GreetingFactory.greeting()
println(greeting.greet())

Welcome to my blog.

60922204

Leave a Reply

Your email address will not be published. Required fields are marked *