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!

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.

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() // "..."

Anything you can code, I can code better (The IKEA Effect)

I am fascinated by cognitive biases. I hope you’ll find them interesting, too, because I plan to discuss several of them on this blog as they pertain to software development. The first one I would like to write about is a blind spot that a lot of us have when it comes to code we wrote.

The IKEA Effect boils down to us putting higher value on something that we created or helped create. I have a lot of pride in my work and I’m not suggesting that pride is a bad thing. However, it can become a hinderance to learning and growth when we irrationally defend our creations.

Here are a few examples of things I’ve seen in my career:

  • Custom solutions for common tools like bug tracking software. This doesn’t make a whole lot of sense when there are solutions created by people who focus solely on this problem.
  • Bubble gum and baling wire used to force a tool to perform a task it wasn’t designed to accomplish because someone has experience with that tool. This is also referred to as the “golden hammer“.
  • Reluctance to try a different approach because a lot of effort was put into the current implementation. This is also referred to as “sunk cost” bias.
  • This is the way we’ve always done it… Ugh.

And, here are a few suggestions to help you steer clear of the IKEA effect:

  1. Don’t take an alternative presented by another person as an attack on your solution. I know communication isn’t every developer’s strong suit, but, as a developer, you should learn to see past that and realize everyone is working toward the same goal. Sometimes you will have the best answer and sometimes you won’t, but you’ll never know unless you’re able to consider ideas other than your own.
  2. Remember that our industry covers a breadth so large that none of us can be an expert at everything. Before you decide to roll your own, consider that there may be a solution created by a 3rd party that has invested a lot more time and energy than you are currently able to pour into solving a particular problem.
  3. Don’t be lazy. It is often easier to understand something we’ve created ourselves than to take time understanding how someone else solved the problem. Fight that urge to default to whatever it is you happen to know and use the opportunity to get a different perspective. Even if you stick with your solution, you may pick up a few tricks that will help you improve it.

In the end, your solution may be the best solution. The important thing is to be able to consider alternatives without bias and be happy to learn when someone presents a better solution. If you’re on a team where your ideas always win out, you may want to consider changing teams. Surrounding myself with people who can challenge me has been one of the greatest sources of growth and success in my career.

Failure as a Catalyst for Growth

Several years ago I was contacted by a recruiter from Google. I was really excited and incredibly humbled that I had even been noticed by a company with their reputation. So, I pulled out my Cormen book (Introduction to Algorithms) and started franticly working through random problems using an IDE. My preparation was not only incomplete, but it was also ill-conceived. My naivety and lack of adequate preparation got me about as far as you might expect: nowhere.

Until recently, I only told a few people about this experience. I was embarrassed. I had failed. The funny thing was that I felt like I was at the top of my game at my current job. I had solved some memory management problems that were plaguing our product. I had been the champion for introducing automated testing to our team’s products. My yearly reviews indicated that I was doing exceptionally well. So, where was the disconnect?

The company I was working for afforded me many interesting projects. I even got to work on some machine learning code. Unfortunately, I hadn’t spent a lot of time thinking about how I would explain that work to a non-coworker. Instead, I ended up responding frequently to questions about my resume with: “I don’t remember the details.”

Next was a coding problem. It wasn’t a very hard coding problem. However, there were a few things that I hadn’t rehearsed that made things difficult.

1) I had been practicing in an IDE with code completion and didn’t realize how much I had been relying on it. I had to write my code in a basic text editor, so I didn’t have all my fancy productivity tools like autocompletion.

2) I had not practiced talking about what I was doing as I was doing it. It turns out that this is something that isn’t hard to master with a little practice.

3) I didn’t work nearly enough problems when I was preparing.

As soon as I hung up the phone with the interviewer, I pulled up my IDE and spit out a working solution in 5 minutes. I was so angry with myself.

Of course, this isn’t the end of my story. It turns out that nothing in my career, to this day, has motivated me more than this single experience. I started buying and reading lots of software development and computer science books. I had missed out on so much! I wish I had found Clean Code, The Pragmatic Programmer, and Code Complete when I was in college. But, there is no point in dwelling on the past. I needed to have these gaps exposed in order to fill them.

In an interview years later, I was told by an interviewer, “You should be careful about putting big words like ‘Metaheuristic Optimization’ on your resume because someone might ask you about that.” I was able to confidently respond with, “I came prepared to talk about that in as much detail as you’d like.” I was disappointed when the interviewer’s response was, “No, no need for that.” However, I did get a job offer after that interview.

All this to say, don’t be discouraged by your failures. Seize them as an opportunity to improve. If you aren’t failing frequently, you probably aren’t growing, so make sure to challenge yourself on a regular basis.

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.

A Metric for Test Quality

One thing that I’ve seen over and over again is that best practices or coding standards that aren’t backed up with some sort of tooling are not consistently followed. I’m sure everyone has been on the team where there is one person that insists on using an ‘m’ instead of an ‘_’ in front of a private field name despite everyone else’s consistent opposite.

Fortunately, there are tools that can red flag this non-conformance and even prevent someone from checking in code that isn’t consistent with those standards. A lot of these tools are known and readily available for use on product code. Less tools and techniques are known for encouraging good testing practices.

One good rule for writing automated tests–unit, functional, or otherwise–is to avoid logic in tests. After all, we’re testing code to validate the logic in our products. We don’t write tests to validate the logic in our tests, so it is best to simply avoid it. Check out Google’s testing blog for a more in-depth treatment: Don’t Put Logic in Tests

So, now that we have agreed on this rule, what metric can we use to ensure we follow it? Cyclomatic complexity. For any of you not familiar with cyclomatic complexity, it is the number of paths through a particular block of code. If there are no decision points (if, switch, etc.) in a given method, then the complexity of that method is 1. You can find static code analyzers that can calculate this metric for just about any language, so what are you waiting for?

Renaming View Controllers Without Breaking the Scene

“Can’t refactor Swift code. Xcode can only refactor C and Objective-C code.” Ugh. I wonder where AppCode is with this…

When creating a new Tabbed Application from the Xcode templates, one of the first things that you’ll want to do is rename the view controllers that are generated for you to something that actually makes sense. Unless, of course, FirstViewController and SecondViewController describe the scenes you’re building. In a lot of the IDEs I use for other languages, something like this is as simple as Refactor -> Rename. Currently, that isn’t an option in Xcode for Swift projects.

So, what happens when you rename the view controller and view controller file? Nothing. Or, so it seems until you start building out the controller and none of your outlets or actions are available to you via Connections. This can be a bit of a head scratcher for someone who hasn’t encountered it before, so below are the rest of the necessary steps for renaming your view controller without disconnecting it from its scene:

  1. Rename your view controller class name and file name
  2. Select the scene that is using the view controller in the Document Outline
  3. In the Identity Inspector, select the renamed view controller in the Class field’s dropdown
And, done!

Growth Mindset

One of the main themes of this blog is learning. A lot of people, including myself, were raised with the understanding that IQ is fixed and that you do the best with what you’ve got. I didn’t realize how limiting that belief was until I discovered that it wasn’t true! More and more research is showing that we are, in fact, able to increase our intelligence.

As it turns out, one of the most helpful things you can do when trying to increase your intelligence is to simply believe that you can. One thing that I’ve observed during my career–and, I am sure is documented by many other sources–is that the people who solve the most insurmountable problems are the ones who don’t know that they are impossible. It seems that the older I get, the harder it is to not quickly dismiss something before giving it a shot. I can’t stress the importance of overcoming this “sad path.” Just try it! You may be very surprised at the result.

Another key factor is learning to embrace failure as merely another mechanism for learning. By pruning the decision trees that represent things unknown to us, we gain a much deeper understanding of whatever it is we’re seeking. In other words, to better understand what is, it is helpful to understand what is not. All those failures start to work like gutter guards (you know, those things that we use to help children learn to bowl) to keep you on a path to success.

Embracing failure as a learning opportunity is a very important part of something called a growth mindset. I first encountered the growth mindset while taking a MOOC taught by Jo Boaler, a renowned professor at Stanford, on learning and teaching math. I highly recommend her course, How to Learn Math. In the course, she talks about some of Carol Dweck’s work, which ended up being a jumping-off point for me. Also, Khan Academy, one of my favorite resources, is also endorsing the growth mindset. Check out their short video about it here.

Do yourself a favor and do a little digging for yourself. Start with the video I linked above and then maybe see what you can find out about Carol Dweck and her research. Check out Jo Boaler’s blog. Get inspired!

Who the lit the fire?

It had been my intention for years to create a blog so that I could share all the interesting things I was learning in my software development career. For whatever reason, I never mustered the required energy to follow through. Enter John Sonmez of simpleprogrammer.com and his free email course on how to start your own blog.

John’s course lays out everything you need to know, step-by-step, to get your blog started and on its way to success. Setting up the blog, in the unadulterated words of Saliva, was as simple as “click, click, boom!” (as I typed that, I felt the immediate need to apologize.) After getting things set up, he shows you how to prepare so that it is easier to maintain momentum as you build your content. And, finally, he shares some tips on how to grow your audience. The coolest part, in my opinion, was the personal encouragement I received from John. What a guy!

I am also about halfway through John’s new book, Soft Skills: The Software Developer’s Life Manual, and recommend it to any software developer looking to up their career game. (And who doesn’t want to do that?) The book is very accessible and chock-full of information that I really wish I had 10 years ago; don’t worry, the information is every bit as valuable today.