Hello, Android!?

Wait! This blog is called The Swift Learner… Why is there a post with “Android” in the title?

Actually, I try not to be a one trick pony; I’m proud to be a polyglot programmer. Also, if you’re building iOS apps, you might consider releasing for Android as well, since it represents a large percentage of the market share.

eband4_xlargecoverIf this sounds interesting to you, I know just the place for you to get started. A few months ago, I had the pleasure of being a technical reviewer for the 4th Edition of Ed Burnette’s new book, “Hello, Android: Introducing Google’s Mobile Development Platform“. It is my opinion that the best way to learn new programming languages, APIs, SDKs, etc. is to use them. Ed’s book will have you writing lots of code that will take you from beginner all the way to releasing your first app in the Google Play store. I know because I worked every exercise in the book. It also taught me how to play Ultimate Tic-Tac-Toe, which I hadn’t encountered before.

As part of a team that just released an Android app, I can tell you that “Hello, Android” does a great job explaining how Android apps work. It also does a good job employing best practices in its examples. Anyway, I hope you find it as useful as I did.

Share

Get Off My Lawn! (Code Ownership)

Ever met a programmer that is territorial about his or her code? Are you that programmer? I’m going to take a couple of minutes to explain why I think that’s a bad idea.

First, let’s consider why a programmer might want to keep other programmers out of “their” code (or, at least, what I assume is their reasoning when I encounter it.)

In order of suspected likelihood:

  1. They don’t trust the other programmers on their team.
  2. They don’t have confidence in their own abilities and are afraid of getting “found out.”
  3. They think that being the only person that understands a particular piece of code grants them job security.

Assuming one of the reasons above is why a person wants exclusive code ownership, here is what they might be missing:

  1. If you don’t trust your team members, you should find out why you feel that way. Perhaps it is an opportunity to mentor someone. This is as beneficial, if not more, to you as it is to them. You gain better understanding of something when you teach it. Also, any decent manager will recognize the value of an employee that improves the people around them.
  2. If you lack confidence in your abilities, maybe you need a mentor. It is much easier to improve if you enlist the help of others trying to reach the same goal. Also, if you involve others and the code ends up failing, the blame is shared by the team and not just you.
  3. Nobody is irreplaceable. I don’t care how good you are or how much you know, there is always someone else that can pick up where you left off. Actually, the easier it is for someone else to learn your code, the better job you did. The reverse is true, too.

One last thing. If you’re working for someone other than yourself, the code probably doesn’t belong to you anyway. It belongs to whoever paid for 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