The Gilded Rose Kata for Swift

If you have never worked through the Gilded Rose kata, you’ve been missing out; it is canon when it comes to coding katas. It is unusual because it provides an initial implementation. Your mission, if you choose to accept it, is to add functionality to this legacy code. By the way, it is a huge mess! In order to make the work manageable, you’ll first have to refactor the existing code.

I wasn’t able to find the initial code in Swift, so I took a couple of minutes to port it. I used the code provided by Emily Bache as a starting point. You should definitely check out her repository if you want to try the kata in different languages.

rose

Share

Watch it.

I recently completed another technical review for The Pragmatic Bookshelf, which has produced (and continues to produce) great technical books. I jumped at the chance to review Jeff Kelley’s new book because it covered a topic that has been greatly anticipated by the Apple community: the Apple Watch.

jkwatch

Even if you have no intention of developing an app for the Apple Watch, I would recommend picking up a copy of Developing for Apple Watch: Your App on Their Wrists.

So, why would you want the book even though you don’t intend to create a Watch app?

1) Jeff gives great insight into the architecture and interactions between the watch and the phone to which it is tethered. Understanding different architectures and designs will certainly give you better intuition into why other things are the way they are in the Appleverse.

2) The code is written in both Obj-C and Swift. This is valuable because of the newness of Swift–there are lots of great libraries that have been written in Obj-C over the years that haven’t been ported to Swift, yet. Being able to make use of these libraries is essential.

3) How do you know you don’t want to write a Watch app if you don’t even know what the device can or can’t do? Learning about it may give you that one in a million idea.

It is an quick read, so if you want to give your brain a quick ++, Jeff’s book is a good choice.

Happy learning.

Share

States That Matter

IceI’ve been spending a little time reviewing design patterns recently, so I thought I would post an example I’ve been working on for the State design pattern. Essentially, the pattern makes it easy for you to change behavior of an object as its state changes.

I didn’t want to copy someone else’s example, so I hope you find this one interesting.

I’m going to create a Water class that has three different states: solid, liquid, and gas. The only difference in behaviors for the states will be their descriptions, which change as the temperature of the water changes. Of course, I don’t think anyone would ever utilize the state pattern for such a simple case, but I’m hoping that it is easy to follow.

The first class I’ll introduce is the Water class. It has an internal state that tracks the temperature and description of the water.

class Water : Printable {
    
    private var state: State! = nil
    
    init() {
        state = Liquid(temperature: 105, water: self)
    }
    
    var temperature: Double {
        get {
            return state.temperature
        }
        set(value) {
            state.temperature = value
        }
    }
    
    var description : String {
        get {
            return state.description
        }
    }
}

 
Next, we’ll need the State class. It provides scaffolding for the various states and also includes some logic that can be shared among states.

class State : Printable {
    
    var water: Water
    
    init(water: Water){
        self.water = water
    }
    
    private(set) var temperature: Double = 0.0 {
        didSet {
            stateChangeCheck()
        }
    }
    
    var description : String {
        get {
            fatalError("\(__FUNCTION__) requires override by subclass.")
        }
    }
    
    private func isSolid() -> Bool {
        return temperature <= 32
    }
    
    private func isLiquid() -> Bool {
        return temperature > 32 && temperature < 212
    }
    
    private func isGas() -> Bool {
        return temperature >= 212
    }
    
    private func stateChangeCheck() {
        fatalError("\(__FUNCTION__) requires override by subclass.")
    }
}

 
Finally, we implement the three states.

class Liquid : State {
    
    init(temperature: Double, water: Water) {
        super.init(water: water)
        self.temperature = temperature
    }
    
    override var description : String {
        get {
            return "Liquid"
        }
    }
    
    private override func stateChangeCheck() {
        if isSolid() {
            water.state = Solid(temperature: temperature, water: water)
        } else if isGas() {
            water.state = Gas(temperature: temperature, water: water)
        }
    }
}

class Solid : State {
    
    init(temperature: Double, water: Water) {
        super.init(water: water)
        self.temperature = temperature
    }
    
    override var description : String {
        get {
            return "Solid"
        }
    }
    
    private override func stateChangeCheck() {
        if isLiquid() {
            water.state = Liquid(temperature: temperature, water: water)
        } else if isGas() {
            water.state = Gas(temperature: temperature, water: water)
        }
    }
}

class Gas : State {
    
    init(temperature: Double, water: Water) {
        super.init(water: water)
        self.temperature = temperature
    }
    
    override var description : String {
        get {
            return "Gas"
        }
    }
    
    private override func stateChangeCheck() {
        if isSolid() {
            water.state = Solid(temperature: temperature, water: water)
        } else if isLiquid() {
            water.state = Liquid(temperature: temperature, water: water)
        }
    }
}

 
I’ve put all of these classes in the same file so that I can use the “private” keyword like I would use the “protected” keyword in other languages. Doing this makes it possible to expose temperature and description, without exposing things I don’t want to expose, like state. Remember, “private” is a little different in Swift than it is in other languages: it limits access to code in the same file (not the same class.)

Let’s see how it works:

var water = Water()
println(water.temperature) // 105.0
println(water.description) // Liquid

water.temperature -= 115
println(water.temperature) // -10.0
println(water.description) // Solid

water.temperature += 225
println(water.temperature) // 215.0
println(water.description) // Gas

 
And there you have it!

Share

Allergies and Dependency Inversion

A couple months ago, I posted about the Law of Demeter and how to keep your classes from requiring knowledge of its dependencies’ dependencies. The code for that post was contrived and I only refactored it far enough to demonstrate the Law of Demeter. However, after posting the article on LinkedIn, someone correctly pointed out that I neglected the Dependency Inversion Principle.

The Dependency Inversion Principle tells us that our higher-level modules should not depend on our lower-level modules. Let’s give dependency injection a try to demonstrate the principle.

Consider the following code:

class LawnService {
    func serviceLawn() {
        Employee().mowGrass()
    }
}

class Employee {
    func mowGrass(){
        LawnMower().cut()
    }
}

class LawnMower {
    func cut(){
        println("Hello allergies!")
    }
}

LawnService().serviceLawn()

 

So, what problems does the example code present?

  1. Isolating the different classes for testing purposes is not possible because of dependency on concrete classes.
  2. The code is not very flexible. What if I wanted to have multiple kinds of lawn mowers?

Let’s start with making it possible to isolate individual classes for testing purposes and see if that technique helps us with our second problem, too.

I need to be able to inject a stub or mock into LawnService, so that I can test it without testing the concrete Employee class. If I make a protocol for the employee and provide a mechanism for injecting an instance into the LawnService class, I should be able to do just that.

// Added a field for an instance of employee 
// that will use whatever concrete is passed 
// in on construction
class LawnService {
    var employee: LawnServiceEmployee
    
    init(_ employee: LawnServiceEmployee) {
        self.employee = employee
    }
    
    func serviceLawn() {
        self.employee.mowGrass()
    }
}

// Extract protocol for lawn service employees
protocol LawnServiceEmployee {
    func mowGrass()
}

// Employee now implemented the new protocol
class Employee: LawnServiceEmployee {
    func mowGrass(){
        LawnMower().cut()
    }
}

// A stub class used for testing
class EmployeeStub: LawnServiceEmployee {
    func mowGrass(){
        // do nothing, we're a stub
    }
}

// Nothing new here
class LawnMower {
    func cut(){
        println("Hello allergies!")
    }
}

// Injecting our real Employee 
// implementation
LawnService(Employee()).serviceLawn()

// Injecting our fake Employee
// implementation for tests
LawnService(EmployeeStub()).serviceLawn()

 

Also, I find it convenient to provide a default implementation if I know I’ll be using a particular concrete most of the time.

class LawnService {
    var employee: LawnServiceEmployee
    
    // Notice that we default to an instance of 
    // Employee
    init(employee: LawnServiceEmployee = Employee()) {
        self.employee = employee
    }
    
    func serviceLawn() {
        self.employee.mowGrass()
    }
}

// This call instantiates Employee and uses it
// rather that requiring it to be passed into
// the init
LawnService().serviceLawn()

 

Let’s do the same thing for lawn mowers, but this time we’ll provide real types instead of a testing fake.

class LawnService {
    var employee: LawnServiceEmployee
    
    init(employee: LawnServiceEmployee = Employee()) {
        self.employee = employee
    }
    
    func serviceLawn() {
        self.employee.mowGrass()
    }
}

protocol LawnServiceEmployee {
    func mowGrass()
}

// Added a field for an instance of lawn mower
// that will use whatever concrete is passed
// in on init
class Employee: LawnServiceEmployee {
    var lawnMower: LawnMower
    
    // defaulting to RidingMower may not be 
    // a good idea...
    init(lawnMower: LawnMower = RidingMower()){
        self.lawnMower = lawnMower
    }
    
    func mowGrass(){
        RidingMower().cut()
    }
}

// Extract protocol for lawn mowers
protocol LawnMower {
    func cut()
}

// One type of lawn mower
class RidingMower: LawnMower {
    func cut(){
        println("Riding along on my gas hog")
    }
}

// Another type of lawn mower
class ReelMower: LawnMower {
    func cut(){
        println("Getting some exercise")
    }
}

var mower = ReelMower()
var employee = Employee(lawnMower: mower)
LawnService(employee: employee).serviceLawn()

 

That’s all well and good, but I think I can clean things up a little more by creating a different kinds of lawn services: an eco-friendly lawn service and a standard lawn service.

class LawnService {
    private var employee: LawnServiceEmployee
    
    init(employee: LawnServiceEmployee) {
        self.employee = employee
    }
    
    func serviceLawn() {
        self.employee.mowGrass()
    }
}

// Standard lawn service has employees
// using riding lawn mowers
class StandardLawnService: LawnService {
    init() {
        var employee = Employee(lawnMower: RidingMower())
        super.init(employee: employee)
    }
}

// Eco-friendly lawn service has employees 
// using reel mowers
class EcoFriendlyLawnService: LawnService {
    init() {
        var employee = Employee(lawnMower: ReelMower())
        super.init(employee: employee)
    }
}

protocol LawnServiceEmployee {
    func mowGrass()
}

class Employee: LawnServiceEmployee {
    var lawnMower: LawnMower
    
    init(lawnMower: LawnMower){
        self.lawnMower = lawnMower
    }
    
    func mowGrass(){
        self.lawnMower.cut()
    }
}

protocol LawnMower {
    func cut()
}

class RidingMower: LawnMower {
    func cut(){
        println("Riding along on my gas hog")
    }
}

class ReelMower: LawnMower {
    func cut(){
        println("Getting some exercise")
    }
}

StandardLawnService().serviceLawn()
EcoFriendlyLawnService().serviceLawn()
Share

Empty or Optional Arrays

I’ve briefly mentioned Swift’s requirement that non-optional variables have a non-nil value in a previous post. I wanted to briefly share what I find to be a best practice: don’t use optional arrays.

So, what is the big difference between these the following declarations?

var heroes: [String] = []
var villains: [String]? = nil

 
What happens when we try to append?

// "Ned Stark" is added to our list of heroes
// exactly what we wanted
heroes.append("Ned Stark")

// nothing happens; the variable is nil
// it is like this line doesn't exist
villains?.append("Petyr Baelish")

 
So, how do we make it so we can add villains?

// add a nil check and create the array if it is nil
if villains == nil {
    villains = []
}

// now we can add a villain
villains?.append("Gregor Clegane")

 
This is just one example of many that requires checking for nil when an optional is in play. In most cases, however, being able to assume that our array is never nil can reduce the amount of checking that we have to perform. This makes our code cleaner and more robust.

What about a function that returns an empty array versus an optional array?

func getVillains() -> [String]? {
    return ["Cersei Lannister", "The Others"]
}

// Unwrapping an array works fine
for villain: String in getVillains()! {
    println(villain)
}

// What if we return nil?
func getVillains() -> [String]? {
    return nil //["Cersei Lannister", "The Others"]
}

// Unwrapping a nil will cause a crash
for villain: String in getVillains()! {
    println(villain)
}

// The correct way to handle the optional array is
// to add a check. This, of course, increases 
// complexity and decreases readability
if let checkedVillains = getVillains() {
    for villain: String in checkedVillains {
        println(villain)
    }
}

 
How would this look if we used an empty array instead?

func getHeroes() -> [String] {
    return ["Tyrion Lannister", "Jon Snow"]
}

// works fine if the array has contents
for hero: String in getHeroes() {
    println(hero)
}

func getHeroes() -> [String] {
    return []//["Tyrion Lannister", "Jon Snow"]
}

// no problems or extra checks required 
// for empty array
for hero: String in getHeroes() {
    println(hero)
}

 
There may be cases where you need to distinguish between a nil and an empty array, requiring the use of an optional. Most of the time, I have found that it just adds extra work.

Share

Exploring Swift’s Generics: Part Deux

Unlike the Mel Brooks movie, History of the World, Part I, the “Exploring Swift’s Generics: Part 1” post will get its sequel. Since I deferred the discussion of protocols, that will be the subject of Part II.

Here is the code that we’ll reuse from the previous example:

class Magic {
    func cast() -> String {
        return ""
    }
}

class BlackMagic: Magic {
    override func cast() -> String {
        return ""
    }
}

class WhiteMagic: Magic {
    override func cast() -> String {
        return ""
    }
}

class Fire: BlackMagic {
    override func cast() -> String {
        return "Fire!"
    }
}

class Ice: BlackMagic {
    override func cast() -> String {
        return "Ice!"
    }
}

class Cure: WhiteMagic {
    override func cast() -> String {
        return "Cure!"
    }
}

class Antidote: WhiteMagic {
    override func cast() -> String {
        return "Antidote!"
    }
}

 
The thing that I found strangest about trying to implement a generic protocol is that you can’t. Protocols use a different syntax altogether. When working with protocols, we’ll use what are called “associated types” to achieve generic-like functionality via the typealias keyword.

Here is how we define the protocol (“mage protocol” sounds pretty awesome, doesn’t it?):

protocol MageProtocol {
    typealias MagicType: Magic

    func castAll(items: [MagicType])
}

 
Notice that we are able to specify a constraint for our type alias, which will come in handy.

Here is one way we could use our protocol to create a mage that only casts black magic:

class BlackMage: MageProtocol {
    typealias MagicType = BlackMagic
    
    func castAll(items: [BlackMagic]) {
        for item in items {
            println(item.cast())
        }
    }
}

BlackMage().castAll([Fire(), Ice()])

 
One shortcoming, in my opinion, of inheriting from a generic class in Swift is that the subclass has to be generic as well. In the case of the protocol, however, there is no need for a generic.

That is not to say that we cannot take advantage of generics:

class Mage<T: Magic> : MageProtocol {
    typealias MagicType = T
    func castAll(items: [T]) {
        for item in items {
            println(item.cast())
        }
    }
}

Mage<WhiteMagic>().castAll([Cure()])

 
Pay attention to the fact that I had to specify a constraint for the generic type that was compatible with the protocol’s type alias.

It seems to me that implementing a protocol with associated types, rather than inheriting from a generic base class, is the cleaner solution (review “Exploring Swift’s Generics: Part 1” for examples of inheriting from a generic class causing weirdness.)

Happy swifting…

Share

Private: It’s Not What You Think

So, here is an interesting tidbit for any of you Swifters that have experience in other languages with access modifiers: “private” doesn’t mean what you assume it means.

Put these to classes in the same file:

public class Secrets {
    private var shhh = "Cannot Hide"
}

public class Exposed : Secrets {
    public func CannotRun() -> String {
        return self.shhh // no compiler error?!
    }
}

 
And, call this:

// This has to be in the same file as the classes
Secrets().shhh // no compiler error?! value is "Cannot Hide"

// This, of course, can be put in a different file
Exposed().CannotRun() // returns "Cannot Hide"

 

Ok. That wasn’t what I was expecting. However, if we read the manual, we find the following: Private access restricts the use of an entity to its own defining source file. Use private access to hide the implementation details of a specific piece of functionality.

I have to admit that I didn’t discover this by reading Apple’s documentation. Actually, it happened by accident when I was playing in a playground. The thing about a playground is that it is just one file, which means that the “private” access modifier has no effect. So, when I made a class field private and was still able to access it, I assumed that there must be a bug in the playground. A quick search on Google straightened me out, though.

So, the next question I asked was “Why?” Why would you want “private” to scope variables, methods, and classes to the current file?

It just so happened that I needed a way to quickly create some fake instances of classes for testing. One of the requirements was that the faked instances should have unique IDs. Prior to Swift 1.2, the “static” keyword wasn’t available, so I came up with the following solution instead:

// UniqueItem.swift file

public class UniqueItem {
    public var id : Int
    
    init() {
        id = 0 // maps to unique database value
    }
}
// FakeUniqueItem.swift file

private var autoId: Int = 0

private func getNextId() -> Int {
    return autoId++
}

public class FakeUniqueItem : UniqueItem {
    override init(){
        super.init()
        id = getNextId()
    }
}
// MyTests.swift file
 
println(FakeUniqueItem().id) // 0
println(FakeUniqueItem().id) // 1
println(FakeUniqueItem().id) // 2

No “static”? No problem. Because both the autoId variable and getNextId() function were private, they weren’t accessible outside the file. I got the effect of a static variable because I was sharing the instance of autoId across instances of my FakeUniqueItem class.

Fortunately, the release of Swift 1.2 added static variables to the mix, so I was able to get rid of my global, private variable and function:

public class FakeUniqueItem : UniqueItem {
    private static var autoId : Int = 0
    
    override init(){
        super.init()
        id = FakeUniqueItem.autoId++
    }
}

So there you have it. My story of how I discovered what “private” means to Swift. If you can think of other ways to leverage it, please leave a comment!

Share

Exploring Swift’s Generics: Part 1

I think using magic for my generics examples captures the mystical aura that surrounds Swift’s generic capabilities. Some of the behaviors are very different than what I’m used to seeing in other languages.

Let’s build some context.

Define a base class for magic:

class Magic {
    func cast() -> String {
        return ""
    }
}

 
Define base classes for different categories of magic:

class BlackMagic: Magic {
    override func cast() -> String {
        return ""
    }
}

class WhiteMagic: Magic {
    override func cast() -> String {
        return ""
    }
}

 
Implement some black magic:

class Fire: BlackMagic {
    override func cast() -> String {
        return "Fire!"
    }
}

class Ice: BlackMagic {
    override func cast() -> String {
        return "Ice!"
    }
}

 
Implement some white magic:

class Cure: WhiteMagic {
    override func cast() -> String {
        return "Cure!"
    }
}

class Antidote: WhiteMagic {
    override func cast() -> String {
        return "Antidote!"
    }
}

 
And, finally, define a magic user:

class Mage<T: Magic> {
    
    func castAll(items: [T]) {
        for item in items {
            println(item.cast())
        }
    }
}

 

Now that we have plenty of boiler plate code, let’s look at something a little more interesting. I want to create a mage that can only cast black magic. My initial thought was to do something like this:

class BlackMage : Mage<BlackMagic> { }

 
Unfortunately, in Swift this causes the following error: “classes derived from generic classes must also be generic” Hrm…

You may be thinking that creating the BlackMage class isn’t necessary. After all, we can just specify the type when we create our variable:

var blackMage = Mage<BlackMagic>()

 
But, for the sake of argument, let’s assume that I want to have functions on my BlackMage class that aren’t on my WhiteMage class and vice versa.

So, it is required that classes derived from a generic class also be generic classes. Can I assume that the generic type for my derived class is related to the base class’s generic type? Nope.

class MeaningOfLife {
    func answer() -> Int { return 42 }
}

class BlackMage<T: MeaningOfLife> : Mage<BlackMagic> {
    func compute(meaningOfLife: T){
        meaningOfLife.answer()
    }
}

BlackMage<MeaningOfLife>().castAll([Fire(), Ice()])
BlackMage<MeaningOfLife>().compute(MeaningOfLife())

 
Why does a derived class have to be generic if it’s base class is generic (especially when the derived class’s generic type has nothing to do with the base classes generic type)? I don’t have a clue… If any knowledgeable readers of the blog would like to chime in, I’d be happy to learn something from them.

The takeaway is this: when specifying a generic type for a class that derives from another generic, the specified type has no impact on the base class–it only specifies the type for generics in the derived class.

You may be wondering why I didn’t use protocols for Magic, BlackMagic, and WhiteMagic. It seems that using protocols also has some interesting effects on generics, but I’m going to save that for another post.

Share

The Swift Brown Fox Says …

I wanted a way to include several topics in one post for beginner Swifters, so here you go:

  • A silly meme
  • A simple protocol
  • Multiple simple implementations of a protocol
  • Pseudo-random number generation within a range
  • Null (Nil) Object Pattern
  • Make a string lowercase

I’ll be referencing a meme/song, “What Does the Fox Say?“, because I couldn’t think of anything better.

A simple protocol that requires all Animals to “say” something:

public protocol Animal {
    func say() -> String
}

 

Some simple protocol implementations for common animals:

public class Dog: Animal {
    public func say() -> String { return "woof" }
}

public class Cat: Animal {
    public func say() -> String { return "meow" }
}

public class Bird: Animal {
    public func say() -> String { return "tweet" }
}

public class Mouse: Animal {
    public func say() -> String { return "squeak" }
}

public class Cow: Animal {
    public func say() -> String { return "moo" }
}

public class Frog: Animal {
    public func say() -> String { return "croak" }
}

public class Elephant: Animal {
    public func say() -> String { return "toot" }
}

public class Duck: Animal {
    public func say() -> String { return "quack" }
}

public class Fish: Animal {
    public func say() -> String { return "blub" }
}

public class Seal: Animal {
    public func say() -> String { return "ow ow ow" }
}

 

Randomly selecting from a list of “sayings” from an unusual animal:

public class Fox: Animal {
    private let phrases = [ "Ring-ding-ding-ding-dingeringeding!",
                            "Gering-ding-ding-ding-dingeringeding!",
                            "Wa-pa-pa-pa-pa-pa-pow!",
                            "Hatee-hatee-hatee-ho!",
                            "Joff-tchoff-tchoff-tchoffo-tchoffo-tchoff!",
                            "Jacha-chacha-chacha-chow!",
                            "Fraka-kaka-kaka-kaka-kow!",
                            "A-hee-ahee ha-hee!",
                            "A-oo-oo-oo-ooo!",
                            "Woo-oo-oo-ooo!"]
    
    public func say() -> String {
        let numberOfPhrases = UInt32(phrases.count)
        let index = Int(arc4random_uniform(numberOfPhrases))
        return phrases[index]
    }
}

 

One of the things I really think I like about Swift is that if you don’t declare a variable as optional (using the ?), it is guaranteed to have a value. You can leverage the Null(Nil) Object Pattern for unknown animals so that you never have to check for nil:

public class NullAnimal: Animal {
    public func say() -> String { return "..." }
}

 

Converting a string to lowercase for more robust matching:

func whatDoesThe(name: String) -> Animal {
    switch(name.lowercaseString){
        case "dog": return Dog()
        case "cat": return Cat()
        case "bird": return Bird()
        case "mouse": return Mouse()
        case "cow": return Cow()
        case "frog": return Frog()
        case "elephant": return Elephant()
        case "duck": return Duck()
        case "fish": return Fish()
        case "seal": return Seal()
        case "fox": return Fox()
        default: return NullAnimal()
    }
}

 

Playing with our new toy:

whatDoesThe("dog").say() // "woof"
whatDoesThe("fox").say() // randomly selected phrase
whatDoesThe("liger").say() // "..."
Share

The Law of Demeter and the 9th Circle of Hell

There are ways to make your code a living nightmare to test. Most of them involve tight coupling. To me, there is nothing worse than trying to mock multiple layers of dependencies in order to test some otherwise simple block of code.

Consider the following code:

func doubleSomethingUseful(does: Does) -> Int {
    return 2 * does.something().useful().eventually()
}

class Does {
    func something() -> Something {
        return Something()
    }
}

class Something {
    func useful() -> Useful {
        return Useful()
    }
}

class Useful {
    func eventually() -> Int {
        return 1
    }
}

If I’m trying to test doubleSomethingUseful(), I have to mock an instance of the Does class so that the something() method can return a mock of the Something class. The mock of the Something class has to return a mock instance of the Useful class when the useful() method is called. And, all this so that the mock instance of the Useful class can return some predetermined test value when the eventually() method is called.

Enter the Law of Demeter (or principle of least knowledge.) The general idea is that a class should not expose its dependencies to its consumers. Instead, it should expose the functionality of its dependencies through wrapper methods. This is a form of information hiding. Click here for an in-depth explanation.

Here is what it might look like for my contrived example:

class Does {    
    func somethingUsefulNow() -> Int {
        return Something().usefulNow()
    }
}

class Something {
    func usefulNow() -> Int {
        return Useful().eventually()
    }
}

class Useful {
    func eventually() -> Int {
        return 1
    }
}

func doubleSomethingUseful(does: Does) -> Int {
    return 2 * does.somethingUsefulNow()
}

Notice that now I only have to mock the somethingUsefulNow() method on the Does class and have it return the predetermined test value. I don’t have to worry about any of its dependencies.

In Dante’s Inferno, the 9th circle of hell is reserved for traitors. Traitors are there because “their acts involve betraying a special relationship of some kind.” See more on the Wikipedia article. Let’s not betray that special relationship between objects, keeping the details where they belong.

UPDATE: This post addresses the Law of Demeter, but there is more to properly decoupling code! Click here to learn about Dependency Inversion.

Share