It’s ok to ship your shitty code (kind of)

8 Jul

Jared Sinclair talks about writing / shipping “shitty code” to keep moving forward.

a fun app has nothing to do with clean code.

I think he’s absolutely right. There’s a time to learn and then there’s a time to ship. Decide which you want to do. It’s likely you’ll also learn quite a bit while shipping your crap code too, which can be applied to your next project.

One word of caution though. While your writing your crap code, you probably want to keep in the back of your mind how you might refactor it later. Don’t worry so much about fixing it now, like Jared said leave a FIXME: comment and move on. Just don’t code yourself into a corner either. The best code isn’t prefect the first time, it’s easily refactorable.

Open Sourcing a Clock

6 Jul

In my ongoing quest to open source more of my work, I’ve open sourced my binary clock app 0’Clock today.

BinaryClockTicking

Admittedly there isn’t much to it. It is just a clock after all. So instead of posting the original Objective-C source, I’ve rewritten it in Swift. If you know someone just getting started with Swift, it might be an easy introduction project. Plus, who doesn’t like a fine binary clock?

One interesting change I decided to make while rewriting it is how to handle setting the LEDs On or Off for a given column. Before I was just using a switch statement, which was easy enough. It went something like this…

func setValue(value: Int, forColumn col: Int) {
    // Turn LEDs for given column OFF
    for row in 0...rows {
        // set LED for row OFF
        setLEDon(false, forColumn: col, row: row)
    }

    // Now turn the desired LEDs ON
    switch value {
        case 1:
        setLEDon(true, forColumn: col, row: 0)
        case 2:
        setLEDon(true, forColumn: col, row: 1)
        case 3:
        setLEDon(true, forColumn: col, row: 0)
        setLEDon(true, forColumn: col, row: 1)
        ...
        case 9:
        setLEDon(true, forColumn: col, row: 0)
        setLEDon(true, forColumn: col, row: 3)
    }
}

While it worked it wasn’t exactly elegant. The logic was easy enough to follow, mainly because there are a small amount of cases and only one kind of action to be taken in each case.

But here’s another way to accomplish the same goal…

func setValue(value: Int, forColumn col: Int) {
    let onesState   = (value & 0b0001) == 0b0001
    let twosState   = (value & 0b0010) == 0b0010
    let foursState  = (value & 0b0100) == 0b0100
    let eightsState = (value & 0b1000) == 0b1000
    
    setLEDon(onesState,   forColumn: col, row: 0)
    setLEDon(twosState,   forColumn: col, row: 1)
    setLEDon(foursState,  forColumn: col, row: 2)
    setLEDon(eightsState, forColumn: col, row: 3)
}

The 0b prefix tells the compiler that the number is binary, instead of a real number like normal.

While we can debate a little over which one is clearer, the second one is more efficient. But let’s be honest, we’re not worried about efficiency in our little clock app. Clarity is much more valuable in this case. But I would argue that once you grasp the basic bitwise operation that is going on here this version is actually clearer. Plus it’s an opportunity to learn a little about bitwise operations, which I just love.

So for those unfamiliar with bitwise operations let’s dive in a see what exactly is going on here. If you already know all about bitwise operations feel free to skip to the bottom for the repo link.

In order to show a number as a binary representation using rows of LEDs we need someway to decide which rows should be lit and which ones should be turned off. In the old way we turned off all the LEDs for a given column and then checked for each possible number 0-9 turning on the corresponding rows as needed. In the new method we’re checking each binary bit of a given number to see if that power of 2 is 1 (On) or 0 (Off) and then turning the LED for that row On or Off to match.

First, a short math refresher is in order…When we say 11 we all know what that means; we learn at a very early age that 11 really means 1 x 10 + 1, or more simply 10 + 1. Let’s take a look at a few more examples…

33
100s 10s 1s
0 3 3
0 x 100 + 3 x 10 + 3 x 1

 

512
100s 10s 1s
5 1 2
5 x 100 + 1 x 10 + 2 x 1

 

We can think about binary numbers in the same basic way; just instead of dealing with powers of 10, we’re dealing with powers of 2. And we indicate that a power of 2 is “On” by showing a 1 in its place, or “Off” by showing a 0 in its place. This is where we get the 1’s and 0’s for binary from.

2
4s 2s 1s
0 1 0
0 x 4  + 1 x 2 + 0 x 1

 

5
4s 2s 1s
1 0 1
1 x 4  + 0 x 2 + 1 x 1

 

Ok, now for a brief discussion about bitwise operations. A bitwise operation is just a way of saying we’re going to manipulate a set of bits in some way. In math we normally talk about operations like addition, subtraction, multiplication, and division. In binary there is a different set of operations we can perform and we call them bitwise operations. These include AND, OR, XOR, NOT, and a few others. But for today we’ll just be discussing AND.

Just like in math were we represent addition with a + symbol we represent the AND operation with the & symbol.

The AND operation takes two bits and if they are both 1 the result will be 1, otherwise the result will be 0. Here’s an example where value is the input number and mask is the binary number we AND it with. This style of using AND is called masking, because we “mask” out the bits we don’t care about, leaving only the bit (or bits) we do care about in the result.

5 & 1 5 & 2 5 & 4 5 & 8
Value 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1
Mask 0 0 0 1 0 0 1 0 0 1 0 0 1 0 0 0
Result 0 0 0 1 0 0 0 0  0 1 0 0 0 0 0 0

 

So in that scenario we’re left with 1 is On, 2 is Off, 4 is On, and 8 is Off. Or put more simply 1 + 4, which of course equals 5, the number we gave it.

Ok, with that out of the way, let’s take a look at the code again.

Here’s how the code evaluates out if the value was 5 (or 0101 in binary)

let onesState = (value  & 0b0001) == 0b0001 // step 1
let onesState = (0b0101 & 0b0001) == 0b0001 // step 2
let onesState = 0b0001 == 0b0001            // step 3
let onesState = true                        // result

let twosState = (value  & 0b0010) == 0b0010
let twosState = (0b0101 & 0b0010) == 0b0010
let twosState = 0b0000 == 0b0010
let twosState = false

let foursState = (value  & 0b0100) == 0b0100
let foursState = (0b0101 & 0b0100) == 0b0100
let foursState = 0b0100 == 0b0100
let foursState = true

let eightsState = (value  & 0b1000) == 0b1000
let eightsState = (0b0101 & 0b1000) == 0b1000
let eightsState = 0b0000 == 0b1000
let eightsState = false

So with that we have the following results

setLEDon(onesState,   forColumn: col, row: 0)
setLEDon(twosState,   forColumn: col, row: 1)
setLEDon(foursState,  forColumn: col, row: 2)
setLEDon(eightsState, forColumn: col, row: 3)

Which becomes…

setLEDon(true,  forColumn: col, row: 0)
setLEDon(false, forColumn: col, row: 1)
setLEDon(true,  forColumn: col, row: 2)
setLEDon(false, forColumn: col, row: 3)

This allows us to set the LEDs precisely to the desired state given any number.

Now I’m not arguing that bitwise operations are the solution to all your problems, and it can be easy to create some obscure and complicated code using them. But they are a very valuable tool to have in your toolbox, and, I think, too often over looked.

Here’s the repo on GitHub.

KVC in Swift (Part 2)

3 Jul

Continuing my attempt at making KVC in Swift

First some quick follow-up:

Paul Lynch mentions on twitter that KVC has actually been around since NeXTSTEP 3.3 (or maybe earlier).

David Owens shows us how simple it is to convert the valueForKey: method to generics.


 

This time around we’ll integrate David’s generic functionality, see how subscripting with generics still isn’t quite there, and extend our KVC protocol to implement valueForKeyPath:

First up, switching to generics – where we can.

In our KVC protocol change valueForKey: to the following

func valueForKey(key : String) -> T?

Then in the KVC extension change the valueForKey: default implementation to this:

func valueForKey<T>(key : String) -> T? {

    let mirror = reflect(self)
    
    for index in 0 ..< mirror.count {
        let (childKey, childMirror) = mirror[index]
        if childKey == key {
            return childMirror.value as? T
        }
    }
    return nil
}

You probably noticed the only real difference is replacing Any with T. T is just a placeholder for a type, a generic type if you will. We could have just as well named it MySuperAwesomeGenericType, but we’re not crazy.

Generic functions can work with any type. The actual type that will be used in place of T will be determined each time valueForKey is called. Confusing? Maybe this will help…

Before, if we had called valueForKey: it would return a type of Any.

let s = aValue.valueForKey("someString")

We can’t do anything useful without casting the type.

let s = aValue.valueForKey("someString") as? String

With generics we can write this more naturally and it will return the type we specify.

let s : String? = aValue.valueForKey("someString")

It would be really nice if the compiler could infer the type entirely, but it’s a start.

Unfortunately this doesn’t translate directly to subscripting.

You can’t just switch out the Any? with T? here

subscript (key : String) -> T?

The compiler will complain that it doesn’t know what T is. I think there might be a way around this by using typealias. If you know of a way to make the subscript generic I would love to hear about it (@leemorgan).

OK. Now that we’ve cleaned that up a bit. Let’s take a look at our next method to implement, valueForKeyPath:

Unlike valueForPath: which will only let you get the value of a given object, valueForKeyPath: will evaluate a chain of properties and return the final link’s value.

We’ll get started by adding the prototype to our KVC protocol

func valueForKeyPath<T>(keyPath : String) -> T?

Then in our KVC extension we’ll implement it like so…

func valueForKeyPath<T>(keyPath : String) -> T? {
    
    let keys = split(keyPath.characters){$0 == "."}.map{String($0)}
    var mirror = reflect(self)
    
    for key in keys {
        for index in 0 ..< mirror.count {
            let (childKey, childMirror) = mirror[index]
            if childKey == key {
                if childKey == keys.last {
                    return childMirror.value as? T
                }
                else {
                    mirror = childMirror
                }
            }
        }
    }
    return nil
}

Most of this should look very familiar, but there’s two parts that need explaining…

let keys = split(keyPath.characters){$0 == "."}.map{String($0)}

There’s a lot going on in that line, but once we break it down it’s not that bad.

In Swift 2 you can’t use split() on String anymore. To get around this we use the characters property of String and split whenever we encounter a “.”

Next, since we’re splitting on the characters we need to convert them back into Strings. We use map to return the split character groups as Strings. (Credit to AirSpeedVelocity for detailing this change in Swift 2, and much more here).

The other part we need to explain is the new loop.

for key in keys {
...
if childKey == keys.last { 
    return childMirror.value as? T 
} 
else { 
    mirror = childMirror 
}

This loop steps through each key in the property key chain. If the key is the last key in the chain we return the value like we did before in valueForKey: otherwise we set mirror to point to the child property and continue the loop.

Now we can quickly transverse a chain of properties

struct myValue : KVC {
    let someString = "Hello World"
}

struct myValueHolder : KVC {
    let aValue = myValue()
}
let bValue = myValueHolder()

let c : String? = bValue.valueForKeyPath("aValue.someString")

And if we change our subscript to use valueForKeyPath: instead of valueForKey: we get this ability for free in subscripting as well.

let c : Any? = bValue["aValue.someString"]

And here’s a cool feature; only the root object needs to conform to the KVC protocol. Even if it’s properties, their children, and so on, don’t conform to KVC you can still access them using valueForKeyPath:

This is still more of a proof of concept than anything, but I’m having fun seeing how KVC could be very natural in Swift.

Updated playground on GitHub here.

KVC in Swift (Part 1)

2 Jul

Last year Brent Simmons wrote about the lack of Key-Value-Coding (KVC) in Swift.

KVC has been around for quite awhile now. Taking a look at the NSKeyValueCoding protocol documentation shows it has been around since OS X 10.0. Which is honestly further back than I remember it being.

It’s not a large API, but it can be very useful.

As the docs say, the basic methods for accessing an object’s values are setValue:forKey:, which sets the value for the property identified by the specified key, and valueForKey:, which returns the value for the property identified by the specified key.

Unfortunately you don’t get those methods in Swift classes and Structs. However, It should be noted that any class that inherits from NSObject does still get KVC in Swift.

Brent mentioned that it would be pretty cool and “Swift-like” to have a syntax in Swift like the following

x["propertyName"]

And I completely agree. So let’s have a go at it.

–––––––––––––––––––––––––––––––––––––

First we need to define a struct to play with.

struct myValue {
    let someString = "Hello World"
    let someNumber = 42
}

let aValue = myValue()

Now we can of course access the properties using the normal syntax like

aValue.someString

But if we don’t know the property we want at compile time and instead have the property’s name as a string we need to do some more work to get at it’s value…

Lets define our KVC protocol

protocol KVC {    
    func valueForKey(key : String) -> Any?
}

For now we’re just going to be implementing  valueForKey: which will allow us to get the value of any property.

We’ll go ahead and extend our KVC protocol and add our default implementation.

extension KVC {
    
    func valueForKey(key : String) -> Any? {
    
        let mirror = reflect(self)
        
        for index in 0 ..< mirror.count {
            let (childKey, childMirror) = mirror[index]
            if childKey == key {
                return childMirror.value
            }
        }
        return nil
    }
}

OK. Let’s break this down a bit. The valueForKey: prototype says that we’re going to take a string and return an optional of Any? Unfortunately I don’t know of a way to have it return a generic (See my follow-up post for the generic version). Or a way to extend Any to make KVC available to all Swift types. If you have any advice let me know on twitter @leemorgan.

The next line is really where things start to get interesting.

let mirror = reflect(self)

Take a look at the reflect() function and you’ll see that it takes a generic and returns MirrorType.

Let’s take a quick sidebar to discuss reflect() and MirrorTypeMirrorType says it “supplies an API for runtime reflection”. Well, what does that mean? It simply means it provides some functions that allow you to get information about a given type / object (e.g. Struct or Class).

If you’re coming from Objective-C then you’re likely familiar with methods like isKindOfClass: and respondsToSelector: those methods are a form of Introspection (Introspection refers to the capability of objects to divulge details about themselves as objects at runtime). You can think of Reflection as a somewhat more powerful form of Introspection.

The parts of MirrorType that we’re interested in are

/// The instance being reflected.
    var value: Any { get }

/// The count of `value`'s logical children.
    var count: Int { get }
    subscript (i: Int) -> (String, MirrorType) { get }

Those methods will allow us to find out what properties our struct has and their values.

Back to our KVC protocol…In the next line we are looping though each property in our struct

for index in 0 ..< mirror.count {

We then get a tuple of the property’s name (childKey) and it’s reflected value (childMirror) using MirrorType‘s subscript method. We don’t so much care about the reflected value (childMirror), it’s just a way for us to access the property’s underlying value.

let (childKey, childMirror) = mirror[index]

Next we check to see if the property (childKey) is the one we’re looking for. If it is, we return it’s value.

if childKey == key {
    return childMirror.value
}

Finally, if we don’t find a match we just return nil

return nil

Now to use this we just need to make our myValue struct conform to the KVC protocol.

struct myValue : KVC { 
    let someString = "Hello World" 
    let someNumber = 42 
}

And then we can use KVC like so

let aValue = myValue()
aValue.valueForKey("someString")

Of course this isn’t the pretty syntax like we wanted, but we can get that really easy. Just add this to our KVC extension

subscript (key : String) -> Any? {
    return self.valueForKey(key)
}

And now we can use it like this

aValue["someString"]

If you’re interested, I’ve posted a Playground demonstrating all this on GitHub.

Alara – Enjoy the sun, safely.

2 Jul

A few years ago a friend of mine, whom I served with in the Air Force, was diagnosed with Melanoma. Upon his diagnosis he was medically discharged from service. I won’t go into the details but suffice to say dealing with melanoma has been very difficult for him and his family.

Melanoma is the most dangerous form of skin cancer and is most often caused by ultraviolet radiation from the sun. When people think of skin cancer they tend to dismiss it as something minor, but Melanoma kills a nearly 10,000 people in the US every year. The American Cancer Society estimates that at present, more than 135,000 new cases of melanoma in the US are diagnosed every year. Fortunately, if recognized and treated early, it is almost always curable. One simple step to prevent Melanoma is limiting your exposure to the sun when the UV radiation is high. Unfortunately, you can’t tell what the UV index is just by looking outside. Ozone depletion, as well as seasonal and weather variations, cause different amounts of UV radiation to reach the Earth at any given time. UV radiation can be high on cloudy days and low on sunny days, it isn’t directly related to the weather.

My wife and I are also light skinned and freckled. Melanoma risk is around double in people with freckles, compared with people without freckles. We have to be careful about how much sun exposure we get. But we also love outdoor activities like running, hiking, and going on walks. I often find myself checking the UV index throughout the day to see when the best time is to go outdoors and enjoy the sun.

We wanted an app that would let us see what the UV index is expected to be throughout the day and to suggest how to best protect ourselves at times when the UV rays are most harmful.

Not finding an app that met our needs, I made one.

I’m proud to announce Alara is available on the AppStore.

 

I’m a software developer, and always wished I could make more of a positive impact on peoples lives. I hope Alara helps in some small way.