Striving for excellence as a software developer

I’ve been a professional software developer for over a decade, and have been writing code since I was a kid. Over the years I have read a lot of advice from software developers with far more experience than me, to expand my thinking and perhaps avoid some mistakes that they once made. Some of my colleagues at various companies have been invaluable sources of insight, as well.  I’ve had enough experience at this point to learn more than a few lessons of my own, some the hard way. I want to give back, and share what I’ve learned with others.

There are basic common sense things about how to write good code that seem obvious once you know them, but are not so obvious to people who have not yet learned those lessons. Some excellent advice is repeated so often that it seems like a cliché to even mention (encapsulation is good!).

I increasingly appreciate the importance and benefits of my received wisdom very gradually. The more code I write and fix, year after year, the more these basic principles of software craftsmanship resonate with me (no seriously, encapsulation really is quite good!)

Many thoughts about what it means to write good code flutter around inside my head. In order to structure these thoughts into something coherent and meaningful I’ve started a living document on GitHub, titled “Sustainable Coding“.

Note: I strongly hesitated to use “sustainable” in the title because it is a popular buzzword. I generally consider the presence of buzzwords to be a warning that something lame is afoot. But, as I explain in the introductory section, it truly is the best word I can find that fits my needs.

If you’re interested in reading my take on what it means to strive for excellence as a software developer, here’s the link:

https://github.com/ijoshsmith/sustainable-coding

This document is a work-in-progress. There’s a lot more that I want to write about, but I’m not in a rush. The document will grow at its own pace.

Posted in Sustainable Coding | 3 Comments

Finding unused resource strings in an iOS app

If you work on an iOS or OS X app that uses Strings files to store localized display text, over time those files can accumulate entries that are no longer used. Perhaps a developer forgot to remove a resource string when refactoring a view controller, or rapidly changing requirements caused a flurry of changes to display text that was never properly cleaned up. If you share my obsession for having no unused or unnecessary things in a codebase, check out my new tool that finds these abandoned strings.

I posted this simple tool on GitHub, along with some information about what the tool can do and what it cannot do.

https://github.com/ijoshsmith/abandoned-strings

Just pass the root directory of your project’s source code as a command line argument and wait a few moments while the program does what would take an OCD-enslaved developer hours to accomplish by hand!

Posted in Swift, Tips and Tricks, Uncategorized | Tagged | Leave a comment

Creating Tic-tac-toe in Swift: User interface

This blog post is the third and final update about my Tic-tac-toe game, written in Swift. The source code is available on GitHub:

https://github.com/ijoshsmith/swift-tic-tac-toe

The app now has a user interface, which allows you to play against the computer or against another person on the same iPhone.

tic-tac-toe

In my article about the Tic-tac-toe gameplay and data model I presented a diagram of domain components, such as the Game and GameBoard classes. The article about artificial intelligence reviewed a perfect-opponent strategy implementation. Now that the app has a user interface which ties these components together, we can see how they fit into the bigger picture.

tic-tac-toe-ui-diagram

The containment relationship between Game and GameBoard (i.e. a Game has a GameBoard) is mirrored by GameViewController and GameBoardView. When GameViewController begins a new game of Tic-tac-toe, it creates a GameBoard used as the data source for both a Game and GameBoardView.

GameViewController-startPlayingGame

The state of a game is visually depicted by GameBoardView. That UIView subclass relies on GameBoardRenderer and GameBoardLayout to perform drawing work.

GameBoardView-drawRect

As the code comments above indicate, creation of the layout and renderer objects is delayed until drawRect(_:) is called to ensure that the view’s graphics context and size are valid. Each object has two properties; one with an underscore prefix to store the object and another, without a prefix, that creates the object when necessary. This is similar to having a custom property accessor that uses an instance variable, in Objective-C.

The rendering work is performed by GameBoardRenderer:

GameBoardRenderer

All of the rendering routines are defined in a private class extension:

GameBoardRenderer-PrivateExt

This code might seem odd if you have experience with CoreGraphics, which is an API of C functions and structures. Thanks to Swift’s all-encompassing support for adding methods to types, I was able to create this wrapper API to hide the ugly details of using CGContext.

CGContextExtension

Rendering a user interface does not, and should not, involve determining the size and location of each thing in the user interface. This separate responsibility is often referred to as layout calculation. I separated these two responsibilities by having the renderer rely on GameBoardLayout for the size and location of every user interface element. The rendering methods seen above use these properties of a layout object:

GameBoardLayout

These properties are all lazy in order to avoid calculating their values more than once. This optimization is appropriate because a layout object is used multiple times throughout a game.

There is a lot more going on in this app, so if you’re interested be sure to clone the repository and dig in!

Posted in Swift, Tic-tac-toe | Tagged , | 1 Comment

Higher-order functions in Swift

This article reviews some very useful higher-order functions available in Swift’s standard library, by showing a simplified implementation of each function. Along the way, I’ll explain how all of the higher-order functions are based on a single loop.

Let’s get higher

Similar to how a rock guitarist’s style can be influenced by listening to jazz, Swift is influenced by functional programming. One of the key functional contributions is polished support for higher-order functions.

By definition, a function is “higher-order” if it has one or more parameters that are functions and/or if it returns a function. In Swift, “passing a function” really means passing a closure, which is the name for an executable block of code. For example:

example-func

The textbook definition of higher-order functions does not suggest how mind-altering it can be to use them. This might not seem like a big deal, but using higher-order functions to process sequences/collections, instead of writing loops, can lead to a new and arguably better way of thinking about data processing. It allows the developer to stop thinking so much about how something should happen and, instead, focus more on what should happen.

Let’s look at simplistic implementations of commonly used higher-order functions in Swift. I’ll show you how they are all based on the reduce function, which itself relies on a single loop.

The code reviewed in this article is available here.

Note: Never use my implementations of these functions, they exist only for explanatory purposes. My functions assume the input and output collections are arrays, for simplicity. My functions are not at all optimized. The standard library methods are much better than mine, so use them instead.

reduce

The most versatile function reviewed here is reduce. Reducing a sequence means transforming many items into a single item. For example, an array of integers could be reduced to the sum of every integer in the array. In this case, a sequence of integers is reduced to a single integer.

An interesting caveat, however, is that the resultant “single item” can itself be a sequence of items. After all, an array is a thing unto itself, despite the fact that it might contain other things. We will see this caveat put to use later.

As I explain here, reducing a sequence involves an accumulator. The accumulator is initialized to a default value, and can be updated when “combining” each element in the sequence.

reduce.png

This function uses a for-in loop to iterate the sequence and combine its elements into a single item. When you use reduce or any of the functions based on it, you’re reusing that loop instead of writing a new one. In a sense, higher-order functions that operate on a sequence enable a form of code reuse that avoids loop duplication.

Here is how reduce can be called:

reduce-usage

Note that I’m using trailing closure syntax for the closure argument. That closure is the combine parameter.

All of the other higher-order functions that process a sequence can be defined in terms of reduce. Let’s check out how…

filter

Taking a subset of items from a collection is a very common programming task. It involves making a yes/no decision for each element in a collection, to determine what to include in a new collection. The filter function handles all of the implementation details except for deciding what the output should contain.

filter.png

This function reduces the input array to an output array by consulting the include closure for each input element. That decision-making logic is provided by the code which calls filter, such as the “is even number” logic in the above example.

map

The map function performs a one-to-one transformation from an input sequence to an output sequence. The output type can differ from the input type.

map

Once again, the reduce function is used to implement a higher-order function. As this example shows, mapping a sequence is another way of “reducing” it.

Here’s a more enticing example. Suppose you have an array of Customer objects but what you need is an array of each Customer’s uniqueID property value. You could create a mutable array, loop over the Customer objects, and add each Customer’s identifier to the array. Or you could transform the customers to their identifiers with one simple line of code, using map. Here’s how that might look using the Swift standard library map method.

customers

This example uses a shorthand argument name ($0) to refer to the first argument passed into the closure, which is a Customer object.

Note that the standard library implements higher-order functions as instance methods, not module-level functions. In other words, the Swift methods are accessed via object.method() unlike my functions, which are accessed directly via function().

flatMap for optionals

The Swift standard library provides another mapping function, named flatMap. There are two versions of this function: one that supports mapping optional values and another that supports mapping a sequence of sequences, such as [[Int]] (i.e. an array of array of integers). Here is my implementation of the version for optional values:

flatMap-optionals

This function is like a mixture of map and filter. It creates a sequence of mapped values, but a mapped value is not added to the output sequence when the closure returns nil. In that sense, returning nil is similar to returning false from a closure passed to the filter function.

Tip: flatMap provides a handy way to remove all nil elements from an array of optional values. Here is how you would do this using the standard library’s flatMap method.

remove-nils

flatMap for sequences

The other version of flatMap is for processing a sequence of sequences. It performs something similar to string concatenation, where the mapped elements for each sub-sequence are joined together into one flat sequence.

flatMap-seq

I’m sure there are more efficient ways to implement this, but I chose to keep this code as straightforward as possible, for the sake of clarity. It, too, is based on reduce, which is just a simple wrapper around a loop.

Parting thought

Higher-order functions that operate on sequences, a seemingly sophisticated concept, can be “reduced” to a simple for-in loop. There is nothing inherently different or special about how they work. What makes them special is how they can elevate your perspective about common programming tasks.

So come on brothers and sisters, let’s get higher.

hippy

Posted in Swift | Tagged , | 3 Comments

Creating Tic-tac-toe in Swift: Artificial intelligence

This blog post is the second update about my Tic-tac-toe game, being written in Swift. The source code is available on GitHub:

https://github.com/ijoshsmith/swift-tic-tac-toe

Over the past week I wrote an intelligent agent which implements the Tic-tac-toe strategy devised by Allen Newell and Herbert Simon in 1972, as explained here. This algorithm is supposed to be a perfect player, meaning it will defeat an imperfect opponent and tie a perfect opponent.

I wrote a method to test that my implementation of the Newell and Simon algorithm is correct when playing against itself. This method is found in GameTests:

GameTests

As seen above, the Game initializer requires a strategy for each player (X and O). Those arguments must adopt the TicTacToeStrategy protocol:

TicTacToeStrategy

It might seem odd that the chosen position is passed to a completion handler, instead of simply being returned from the method, but this design will be necessary later to accommodate a human player.

This protocol is adopted by the intelligent agent:

NewellAndSimonStrategy.png

An instance of this class has an ordered sequence of tactics, each of which adopts the NewellAndSimonTactic protocol.

NewellAndSimonTactic

Note that the NewellAndSimonStrategy initializer defines a list of tactics as a default parameter value. This is a useful technique for enabling unit tests to inject mock objects, which is exactly what I did in NewellAndSimonStrategyTests:

MockTactics

A tactic is a means of determining which position to occupy on a game board. For example, CenterTactic is the simplest tactic in the Newell and Simon strategy:

CenterTactic

A more complicated and interesting example is WinTactic, which leverages the OutcomeAnalyst that Game uses to detect when a game is over.

WinTactic

The behavior of this tactic is verified by unit test methods defined in WinTacticTests:

WinTacticTests

In case you’re curious about that board3x3 function, it is part of a simple domain-specific language (DSL) I created for turning a text diagram of a Tic-tac-toe game into the equivalent GameBoard instance. That DSL code can be found in GameBoard+DSL.swift.

My next major milestone is to create an iOS app that consumes the Tic-tac-toe library I’ve written so far. See you next time!

Next article: Creating Tic-tac-toe in Swift: User Interface

Posted in Swift, Tic-tac-toe, Uncategorized | Tagged , | 1 Comment

Creating Tic-tac-toe in Swift: Gameplay and data model

This blog post is an update on my work-in-progress Tic-tac-toe game, being written in Swift. The source code is available on GitHub:

https://github.com/ijoshsmith/swift-tic-tac-toe

I’ve reached the first major milestone. The program is capable of playing Tic-tac-toe against itself, although there is not yet an intelligent agent deciding where to put each mark on the game board.  Instead, the program has what I call a “scripted strategy” which unit test methods use to advance a game to completion.

Before we get into how that works, here’s a mile-high view of the classes involved so far.

tic-tac-toe-diagram

GameBoard is the data model which stores each mark a player puts on the board.

Game orchestrates gameplay between two players.

OutcomeAnalyst is what Game uses to detect when a game is over.

Player represents a contestant, either human or computer.

TicTacToeStrategy describes an object Player uses to choose where to put a mark.

So far the only class which adopts the TicTacToeStrategy protocol is for testing purposes, named ScriptedStrategy.

ScriptedStrategy

One interesting thing about this class is that it supports a tiny domain-specific language. As seen in the following example from GameTests (slightly modified to fit this blog’s layout), a ScriptedStrategy is created for each player by parsing a text diagram of a Tic-tac-toe board showing where each Player should put its marks.

tied-game-test

Up next I will work on the algorithmic strategy, so that the app’s user will have a challenging opponent to play against. This is a lot of fun!

Next article: Creating Tic-tac-toe in Swift: Artificial Intelligence

Posted in Swift, Tic-tac-toe | Tagged , | 1 Comment

Creating Tic-tac-toe in Swift

Normally I blog about a program I’ve already written. I decided this time to take a different approach, and blog about a Tic-tac-toe program that I’m writing instead. This will give people who are interested in watching a Swift program evolve over time the chance to follow along. As I add new features and refactor the code, I will post about it on this blog.

The repository is on GitHub:

https://github.com/ijoshsmith/swift-tic-tac-toe

My first committed class is GameBoard. It is the data model that stores the state of a game, namely which positions have been marked with X’s and O’s.

That class’s unit tests are here. The test method naming convention I use is:

test_<method-under-test>_<condition>_<expected-result>

You will need the latest Xcode to build this project.

Enjoy!

Next article: Creating Tic-tac-toe in Swift: Gameplay and data model

Posted in Swift, Tic-tac-toe | Tagged , | 3 Comments