Unit testing Core Data-driven apps, fit the second

It took longer than I expected to follow up my previous article on unit testing and Core Data, but here it is.

Note that the pattern presented last time, Remove the Core Data Dependence, is by far my preferred option. If a part of your code doesn’t really depend on managed objects and suchlike, it shouldn’t need them to be present just because it works with (or in) classes that do. The following pattern is recommended only when you aren’t able to abstract away the Core Data-ness of the code under test.

Pattern 2: construct an in-memory Core Data stack. The unit test classes you develop ought to have these, seemingly contradictory properties:

  • no dependence on external state: the tests must run the same way every time they run. That means that the environment for each test must be controlled exactly; dependence on “live” application support files, document files or the user defaults are all no-nos.
  • close approximation to the application environment: you’re interested in how your app runs, not how nice a unit test suite you can create.

To satisfy both of these properties simultaneously, construct a Core Data stack in the test suite which behaves in the same way but which does not use the persistent store (i.e. document files) used by the real app. My preference is to use the in-memory store type, so that every time it is created it is guaranteed to have no reference to any prior state (unlike a file-backed store type, where you have to rely on unlinking the document files and hoping there are no timing issues in the test framework which might cause two tests simultaneously to use the same file).

My test case class interface looks like this (note that this is for a dependent test case bundle that gets embedded into the app; there’s an important reason for that which I’ll come to later). The managed object context will be needed in the test methods to insert new objects, I don’t (yet) need any of the other objects to be visible inside the tests but the same objects must be used in -setUp and -tearDown.

#import <SenTestingKit/SenTestingKit.h>

@interface SomeCoreDataTests : SenTestCase {
NSPersistentStoreCoordinator *coord;
NSManagedObjectContext *ctx;
NSManagedObjectModel *model;
NSPersistentStore *store;
}

@end

The environment for the tests is configured thus. I would have all of the error reporting done in tests, rather than that one lone assertion in -tearDown, because the SenTest framework doesn’t report properly on assertion failures in that method or in -setUp. So the -testThatEnvironmentWorks test method is a bellwether for the test environment being properly set up, but obviously can’t test the results of tear-down because the environment hasn’t been torn down when it runs.


#import "TuneNeedsHighlightingTests.h"

@implementation TuneNeedsHighlightingTests

- (void)setUp
{
model = [[NSManagedObjectModel mergedModelFromBundles: nil] retain];
NSLog(@"model: %@", model);
coord = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: model];
store = [coord addPersistentStoreWithType: NSInMemoryStoreType
configuration: nil
URL: nil
options: nil
error: NULL];
ctx = [[NSManagedObjectContext alloc] init];
[ctx setPersistentStoreCoordinator: coord];
}

- (void)tearDown
{
[ctx release];
ctx = nil;
NSError *error = nil;
STAssertTrue([coord removePersistentStore: store error: &error],
@"couldn't remove persistent store: %@", error);
store = nil;
[coord release];
coord = nil;
[model release];
model = nil;
}

- (void)testThatEnvironmentWorks
{
STAssertNotNil(store, @"no persistent store");
}
@end

The important part is in setting up the managed object model. In using [NSManagedObjectModel mergedModelFromBundles: nil], we get the managed object model derived from loading all MOMs in the main bundle—remembering that this is an injected test framework, that’s the application bundle. In other words the MOM is the same as that created by the app delegate. We get to use the in-memory store as a clean slate every time through, but otherwise the entity definitions and behaviours ought to be identical to those provided by the real app.

Posted in cocoa, CoreData, objc, unittest | 6 Comments

CocoaHeads Swindon, January and February

The next CocoaHeads Swindon will take place on 4th January, at the Glue Pot in Swindon. Get here at 8 for some NSChitChat with your (well, my) local Mac developer community.

There is no February meeting of Swindon CocoaHeads, on account of NSConference Europe taking place in Reading on that weekend. So buy your NSConference ticket and come along to say hi!

Posted in cocoa, cocoaheads, conference, macdevnet | Leave a comment

Nearly the end-of-year review

My first post (Farkers, feel free to replace that with “boobies”) of the year 2009 was a review of 2008’s blog and look forward to 2009. It’s time to do the same for the 2009/2010 blogyear bifecta.

Let’s start with the recap.

2009 was a comparatively quiet year for iamleeg, with a total of 45 posts (including this one). Although I gave up on LiveJournal, leading to an amount of “mission creep” in the content of this blog, I think that the vast increase my use of Twitter led to the decline in post frequency here. I’ve come to use Twitter as a replacement for Usenet, it’s much easier to share opinions and discuss things on Twitter where there’s more of a balanced conversation and less of iamleeg telling the rest of the world how things should work. The other main contributory factor was that I spend my days writing for a living currently, split between authorship, consultation and the MDN security column. I’m often all written out when it comes to the end of the day.

So, the mission creep. 2009 saw this blog become more of a home for ideas long enough to warrant a whole page on the internet, losing its tech focus—directly as a result of dropping LJ, which is where non-tech ideas used to end up. However, statistics show that the tech theme is still prevalent, with only four of the posts being about music or dancing. Security has become both the major topic as well as the popular choice; the most-read article was Beer Improves Perception of Security.

During August and September the focus started to shift towards independent business and contract work, as indeed I made that shift. Self-employment is working well for me, the ability to choose where I focus my effort has let me get a number of things done while still retaining a sense of sanity and a balance with my social life.

So what about next year?

Well, the fact that I have a number of different things to focus on leads to an important choice: I need to either regroup around some specific area or choose to remain a polymath, but either way I need to be more rigorous about defining the boundaries for different tasks. My major project comes to an end early in 2010, and after that it’s time to calm down and take a deep look at what happens next. I have a couple of interesting potential clients lined up, and have put onto the back burner my own application which will definitely see more work. I also have some ideas for personal development which I need to prioritise and get cracking on. The only thing preventing me from moving on a number of different projects is convincing myself I have time for them.

So the blog will fit in with that time-management strategy; I won’t necessarily decide that 9:00-10:14 on a Monday is always blogging time, but will resolve to put aside some time to writing interesting things. One thing I have found is that working on one thing for a whole day means I don’t get much of it done, so factoring that into my plans will let me take advantage of it. Half an hour working on a new article at lunchtime could be the stimulus required to get more out of the afternoon. My weapon of choice for organising my work has always been OmniFocus, it’s time to be more rigorous about using it. It doesn’t actually work well for time allocation, but it does let me see what needs to be done next on the various things I have outstanding.

Obviously what becomes the content of this blog depends on what happens after I’ve shaken down all of those considerations and sorted out what it means to be leeg. Happy new year, and stay tuned to find out what happens.

Posted in meta-interwebs, omnifocus, personal, security, Twitter | Leave a comment

On Operation Chokehold

So Fake Steve Jobs has announced Operation Chokehold, a wireless flashmob in which disgruntled AT&T customers are to use data-intensive apps for an hour in protest at the poor service and reduced investment AT&T provide on their network. At time of writing, Operation Chokehold has 3,000 fans on Facebook – a small fraction of the ∼82M AT&T Mobility subscribers in the U.S. Fake Steve has latterly wondered whether it is illegal (using the “it’s now out of my hands” defence, popular with people who don’t understand what incitement means), and seemingly back-pedalled, considering aloud whether people might try a shorter duration or physical flashmob of AT&T stores instead. It would appear that the FCC (the U.S. agency responsible for regulating national and international communications) has weighed in, declaring a wireless flashmob to be irresponsible and “a significant public safety concern”.

How is it a concern? Due to the way the phones work, you don’t need to the capacity to support all of the users, all of the time, in order to provide a reasonable service. Think of running a file-sharing service like DropBox or Humyo. If you offered up to 10GB storage per customer and have 10,000 customers, then you need 100TB of storage, right? Wrong. That’s the maximum that could be used, but let’s say in practice you find average use to be 100MB/customer. It turns out that 1TB of storage would be the minimum you’d need to satisfy current demand, if you had even 1.5TB then you’d comfortably support the current customer base while allowing for some future use spikes or growth. The question most businesses ask then is not how risky it is to drop below 100% capacity, but how much risk they can accept in their buffer over average capacity. The mobile phone network operates in the same way. To avoid dropped calls you don’t need the bandwidth to support 100% of the phones operating 100% of the time, you need to support the average number of phones the average amount of time, plus a little extra for (hopefully foreseen) additional demand.

The argument by AT&T and the FCC against the wireless flashmob then is that because the network is oversubscribed as an accepted business risk, it would actually be possible for the concerted operation of a large number of users to cause disruption to the network. This eventuality is evinced every year in the early morning of January 1st, as people phone or SMS each other with New Year greetings. People making legitimate calls during this time could be disconnected or unable to place a call at all—while that would undoubtedly make the protest noticed by AT&T it’s that aspect of it which makes it a potential public safety concern. Personally, I find it hard to believe that the network doesn’t have either dedicated capacity or priority quality of service (QoS) treatment for 9-1-1 calls, but it’s possible still that some 9-1-1 calls might not get placed correctly. That’s especially true if the caller’s handset can’t even connect to a tower, which could happen if nearby towers were all saturated with phones making data connections. While it’s possible to mitigate that risk (dedicated cell towers for 9-1-1 service, which emergency calls are handed over to) it would be very expensive to implement. There’s no business need for AT&T to specially support emergency calls, as they don’t make any money from them, so they’d only do that if the FCC mandated it.

But then there are all the non-9-1-1 emergency calls—people phoning their local doctor or hospital, and “business critical” calls made by people who somehow think that their business is critical. Even the day-to-day running of government is at least partially conducted over the regular phone networks, as was seen when the pager traffic from New York on September 11th 2001 got posted to WikiLeaks. These calls are all lumped in with the regular calls, because they are regular calls. The only way to mitigate the risk of dropping these is to increase the capacity of the network, which is exactly the thing that people are saying AT&T don’t do to a satisfactory level. If the contracts on AT&T Mobility are anything like the contracts on UK phone networks, then subscribers don’t have a service level agreement (SLA) with the provider, so there’s no guarantee of provision. The sticking point is the level of expected provision doesn’t match that. If the providers operated multi-tier subscription services like the broadband providers do in the UK, then they probably would do QoS management so that preferential customers get better call service—again, assuming the customers can connect to the cell tower in the first place. But again, that’s a business issue, and if the guy participating in Chokehold has a more expensive plan than the girl trying to phone the hospital, his connection will win.

Will Chokehold fulfil its goal of making AT&T invest more in its infrastructure? I don’t know. Will it actually disrupt public safety services such as 9-1-1? I doubt it. Is it a scale model for a terrorist attack on the communications infrastructure of the US? Certainly not. Much easier to jump down a manhole and snip the cables to the data centres.

Posted in iPhone, security | Leave a comment

Consulting versus micro-ISV development

Reflexions on the software business really is an interesting read. Let me borrow Adrian’s summary of his own post:

Now, here’s an insider tip: if your objective is living a nightmare, tearing yourself apart and swear never touching a keyboard again, choose [consulting]. If your objective is enjoying a healthy life, making money and living long and prosper, choose [your own products].

As the author himself allows, the arguments presented either way are grossly oversimplified. In fact I think there is a very simple axiom underlying what he says, which if untrue moves the balance away from writing your own products and into consulting, contracting or even salaried work. Let me start by introducing some features missed out of the original article. They may, depending on your point of view, be pros or cons. They may also apply to more than one of the roles.

A consultant:

  • builds up relationships with many people and organisations
  • is constantly learning
  • works on numerous different products
  • is often the saviour of projects and businesses
  • gets to choose what the next project is
  • has had the risks identified and managed by his client
  • can focus on two things: writing software, and convincing people to pay him to write software
  • renegotiates when the client’s requirements change

A μISV developer:

  • is in sales, marketing, support, product management, engineering, testing, graphics, legal, finance, IT and HR until she can afford to outsource or employ
  • has no income until version 1.0 is out
  • cannot choose when to put down the next version to work on the next product
  • can work on nothing else
  • works largely alone
  • must constantly find new ways to sell the same few products
  • must pay for her own training and development

A salaried developer:

  • may only work on what the managers want
  • has a legal minimum level of security
  • can rely on a number of other people to help out
  • can look to other staff to do tasks unrelated to his mission
  • gets paid holiday, sick and parental leave
  • can agree a personal development plan with the highers-up
  • owns none of the work he creates

I think the axiom underpinning Adrian Kosmaczewski’s article is: happiness ∝ creative freedom. Does that apply to you? Take the list of things I’ve defined above, and the list of things in the original article, and put them not into “μISV vs. consultant” but “excited vs. anxious vs. apathetic”. Now, this is more likely to say something about your personality than about whether one job is better than another. Do you enjoy risks? Would you accept a bigger risk in order to get more freedom? More money? Would you trade the other way? Do you see each non-software-developing activity as necessary, fun, an imposition, or something else?

So thankyou, Adrian, for making me think, and for setting out some of the stalls of two potential careers in software. Unfortunately I don’t think your conclusion is as true as you do.

Posted in Business, marketing, metadev, mythicalmanmonth | 6 Comments

Poke the other one, it’s got bells on

Originally the title for this post was to be “Why a Morris organisation should adopt social media (and why they probably won’t)”, with what is now the title being reduced to the rank of a subtitle. Then I remembered that I am leeg, and as such humour is always better than content (certainly a lot easier). So we have the title you see before you.

Please bear in mind when reading the epistle located below that I’m fairly new to the whole world of Morris, and especially new to its political fiddle-faddle. If anything here seems to stereotype people or their motives, it’s based on the experience of someone who can at best be considered an informed outsider. [And for those who are even more of an outsider than I am, Morris dancing is the name for a roughly-related collection of traditional English dancing styles, performed by groups called sides or teams. It’s both good fun and a decent workout, give it a go.]

It seems to have been a problem for at least the length of my lifetime that Morris lacks any relevance to what, for sake of pomposity, I shall refer to as the man on the Clapham omnibus — taking the irony fully on board. That your average person sees no reason to engage with or appreciate the Morris. Why? Has the Morris really made much of an attempt to engage with or appreciate the life of the average person? Not, I would argue, at any concerted or large-scale level, leaving the final impression most people have of Morris dancers the same as their first impression: a bunch of old men in silly clothes hitting each other with sticks.

So, shouldn’t I have mentioned the social media by now? Yes, I’m just coming to that, it’s only a couple of paragraphs away now. First some context. There are three umbrella organisations for the Morris in the UK: the Morris Ring is the oldest, with its infamous men-only rules; the Morris Federation (whose website was broken at time of writing) started life as the less-infamously women-only Women’s Morris Federation; then there’s Open Morris, which to my knowledge has never had any infamous membership rules and is the youngest of the three organisations. None of these organisations takes on a promotional or advocacy rôle — or at least, if they do, they’ve done a bad job of it. They represent more of an internal support network, offering guidance, information, training and the like to the sides. If you don’t believe that they aren’t promotional bodies, take a look at their websites.

As a digression I will use this paragraph to mention the English Folk Dance and Song Society, which does indeed have advocacy, promotion and outreach as its goals. However, I’m not aware what the relationship between the EFDSS and any of the sides or morris umbrella groups is. That’s definitely lack of knowledge on my part, rather than indicative of a lack of interaction. Certainly the three groups named above have all contributed to the EFDSS’s magazine, ED&S, recently, although I haven’t read their contributions. There’s a lot of morris-related material in the EFDSS archives, too. By the way, I’m reliably informed that the society’s name is pronounced “EFd&#x0259s”.

There are, then, four groups identified who either do, or could take on if they so chose, a rôle in promoting the morris to the general public. Given the continued and increasing popularity that web-based media, particularly social media, has in the world, let’s examine the part each of these groups plays.

  • Twitter Presences: 0.
  • Official Facebook Presences: 2. The EFDSS has a fan page. There’s a group for Open Morris too, which looks like it could be run by the real organisation. I think that counts as user-generated content is part of the world of social media.
  • Official YouTube Channels: 0. Or at least none that I could find.
  • Myspace Presences: 1. EFDSS again.
  • Podcasts: 0.
  • RSS feeds (that scraping noise you hear, it’s the bottom of the barrel): 1. It’s the Morris Ring’s news feed. I nearly fell out of my chair.
  • For completeness, I’ll also mention that there’s an unofficial mailing list called MDDL (Morris Dancing Discussion List) which is very active with a strong signal-to-noise ratio.

Now, why should any of this be important? Well, as you’re reading this, you’re consuming a blog. You either thought “I would like to know what leeg is up to, I’ll read his blog”, “I heard that some guy on the interwebs really lays into morris dancing organisations, I’ll check it out”, or something else which made you decide to spend time engaging with social media and user-generated content on the web. That’s time which the various morris groups could have spent injecting your brain with Morris Dancing. Are they doing that? No. They’re writing internal newsletters bemoaning the lack of traditional dancing in the national curriculum, and press releases for the Torygraph to pick up, claiming that morris dancing is dying out because all of the practitioners are getting too old. In fact, it’s been nearly a year since that last one was done.

The problem is that you and I and everybody else don’t give a shit about the Morris Ring Circular or their press releases, in the same way we give a shit about, say, procrastinating on YouTube, following interesting people on Twitter, catching up with friends on Facebook and so on. The people who complain about morris dancing fading into irrelevance are even managing to complain about it in an irrelevant fashion. Irony. They’re doing it right.

And the most galling thing is that the social media and traditional dancing could go together so well. Take a photo like this, which I took at the Morris 18-30 in WakeField:

You may wonder why everyone’s wearing different costumes; well the answer is that they’re from different sides. A mash-up could tag the dancers with their side’s name, and a link to their website. Your next question would, of course, be the same as mine: “but where the hell is Packington, anyway?” A map showing the location of each side could be available, perhaps even showing proximity of their practice venue to your current location and when they’ll next be practising (please, do not get me started on the existing SideFinder pages. You would not like what I would become). Had I remembered what dance was being danced (I think it’s Skirmishes, though I’m sure someone would be able to spot it from the photo), then information about that dance and videos of sides performing it could be available.

[Another aside: the relative obscurity of some teams’ locations has consequences for those teams’ performances. As an example, the fool of Adderbury Morris always wears a hat made of fox skin during the dances. This is because when the first team was formed, the fool went home to tell his wife about his new position. Her response is recorded as being “Adderbury? Wear the fox hat”.]

“Aha,” you hypothetically cry. “But I would not have seen the photo in the first place, had you not talked about it on your blog.” Indeed no, but the point of blogs, Twitter, Tumblr and the like is that you get personal recommendations from people you either trust or consider expert in their field. So I think it’s fair to have introduced the photo in that way; and that there’s a space online for personal recommendation of trying out morris dancing. And that there ought to be some organisation helping people to do that promotion.

Incidentally, the Morris 18-30 is actually a good example of a group (or phenomenon, I suppose) building a decent website with good amounts of information, and providing an easy way for people to get their photos online. There are many sides which have done the same; Westminster Morris Men’s YouTube channel has a decent set of videos including some from the archives. My point is not that this information is not being made available, nor that an effort is not being made — I chose the 18-30 photo for my example because I took the picture and have the right to re-use it in this blog.

I don’t think that the fact some sides do well at promoting themselves affects my argument; those who don’t have the skills or resources to do this work themselves are not being helped by the national/international bodies. People who might be interested in traditional dancing aren’t finding out about it, because the nearest side who have any skill at marketing are in the next county. In a world where information can travel the world in a fraction of a second, that’s ludicrous.

So the fact that 18-30 has a good website where people can share information easily is a good thing. The various mash-up suggestions I made would all be good improvements, and were they implemented by an umbrella group then everyone could take advantage of them. My point is that the umbrella organisations should be taking and collating the vast amount of morris-related information out there, and making it easy for people who are not (yet) in the morris to find. They should be using it to promote the dance form and the social activities that surround it, but they aren’t. They should be providing a central service to make it easier for sides to share their own material, but they aren’t. They should be taking their existing archives and making them available online, but they aren’t. They should be looking at the innovations made by some of their members and applying them at the international level, but aren’t.

In addition to existing content, there is plenty of scope for promotional material based on novel content distributed over the internet. The dances, music and even pub sessions could make great segments for a vlog or video podcast. Even mini-instructionals could be presented as video podcasts or on a YouTube channel, so that people can try things out without having to join a side first. “What’s the point of dancing a team dance on your own?” — leaving jigs aside as PhD-level morris, some people may just want to find out whether they can do some of the basic stuff on their own before turning up to a practice session. If you’re not sure whether you want to take part in an activity, would you have your first try in front of twenty people who’ve been doing it for years, and are each armed with a big stick? Maybe not.

So there’s plenty of space for morris information to be distributed digitally. But, really, who gives a toss? That’s where the promotional aspect comes in. I’ve already mentioned the personal level of promotion through Twitter and the like. There are obvious places where morris could be promoted; what’s on guides, tourism sites, tradition-reporting sites and the like. But how about novel audiences? Dancers, like many British people, enjoy a Beer in the Evening. Given decent information feeds like the things I described a few paragraphs ago, morris data could be highly Mashable, featuring in those little Facebook games. If people like what they see, they will Digg it. Were one of the umbrella orgs to hire a dashing, intelligent, handsome developer-dancer they could even promote through the iPhone app store (though where would they find such a person?).

And what Americans like to call “the kicker” is this: real people drink beer, use websites and download apps. Most of the dancers I’ve met are either from families of dancers or already had interest in folk music; in that sense the person on the street is an “unexploited vertical” for the marketers of morris, and probably has been since the end of the first world war.

OK, so that’s what could be done, who should be doing it, and why. Is it fair for me to put words in the mouths of the umbrella orgs in suggesting why they aren’t currently doing it? No, but I will anyway. If you think this blog is fair, then I’ve got a slightly-used iBook I’ll sell you for a great price.

I think that for a large part, the people in charge probably just don’t use and therefore don’t understand the potential of social media. But that doesn’t explain why the morris umbrella organisations don’t do any promotion whatsoever. At least one of the organisations may be wary of getting too much publicity for themselves; I’m not a lawyer of course, but the equality bill currently awaiting its 3rd reading in the House of Commons could require the Morris Ring to change its membership rules, as it "Extends discrimination protection in the terms of membership and benefits for private clubs and associations". I expect there isn’t much in the way of training available to the organisations in the general field of marketing. I’m not sure what kind of budgets these groups run on, but maybe the three of them together could afford a part-time marketer.

Of course, there’s some appeal to the idea that you’re in a secret society, isn’t there? It’s quite exciting to think that you do something enjoyed by few others, and it’s easier to become important in smaller social groups. Not that I’m suggesting that’s a related point, oh no.

I apologise for writing such a long post. I didn’t have the time to write a shorter one.

Posted in facebook, marketing, music, Twitter | 3 Comments

Unfamiliar territory

People who’ve seen me play music more than once will probably have noticed more than a slight sense of a pattern – give me a fiddle (or if you’re really unlucky then I’ll bring my own), and I play English folk music. Give me a guitar and I’ll play rock and roll. That’s just what my fingers are used to – to me the guitar has six strings of rockabilly and the fiddle has four strings of constant billy. No, I didn’t write this piece just to get that pun in, though I am glad that I did. I can now go to my grave a happy man, safe in the knowledge that I have compared fishes flying over mountains with blues-derived country music. Classy.

Well, I think it’s time to change things around a bit. I want to leave my violin all shook up, and my guitar all in a garden green. It probably sounds quite easy, given that I already know all the tunes, and just want to play them on different instruments, but really it isn’t. There are two important issues which make it hard for me to just swap over.

The first is that in many cases I don’t actually know the tune at all, I just use muscle memory to get my digits moving in the right places for music to occur. That’s particularly true in the case of rock n roll music, where there really aren’t tunes at all. There are just ‘licks’, basic one or two bar figures which are strung together into a twelve bar part. But it’s also true in folk music which has a similarly hypnotic repetition but with longer figures. So taking a tune to a new instrument means discovering what it is I’m actually playing on the first instrument, then trying to reproduce that on the second.

The second issue is that just playing the notes from one instrument on another isn’t necessarily the correct thing to do, nor even particularly easy. For a start guitar strings are tuned to fourths (mainly) while violin strings are to fifths, and as the bridges are different shapes the instruments invite playing a different number of strings simultaneously. So what I need to do is not even to work out how to play the same tune on the other instrument, but what that instrument’s version of the tune should be and how to play that.

I expect that the outcome of this little experiment will be mainly a cacophony, but with some increased understanding of what the instruments can do and how to play them. If I focus on cacophony then I’ll probably get quick results, though.

Posted in music | 1 Comment

Next Swindon CocoaHeads meeting

At one time a quiet market town with no greater claim than to break up the journey between Oxford and Bristol, Swindon is now a bustling hub of Mac and iPhone development activity. The coming meeting of CocoaHeads, at the Glue Pot pub near the train station on Monday October 5th, is a focus of the thriving industry.

I really believe that this coming meeting will be a great one for those of you who’ve never been to a CocoaHeads meeting before. We will be having a roundtable discussion on indie software development and running your own micro-ISV. Whether you are a seasoned indie or just contemplating making the jump and what to find out what’s what, come along to the meeting. Share your anecdotes or questions with a group of like-minded developers and discover how one person can design, develop and market their applications.

You don’t need to register beforehand and there’s no door charge, just turn up and talk Cocoa. If you do want to discuss anything with other Swindon CocoaHeads, please subscribe to the mailing list.

Posted in Business, cocoa, cocoaheads, iPhone | Leave a comment

Unit testing Core Data-driven apps

Needless to say, I’m standing on the shoulders of giants here. Chris Hanson has written a great post on setting up the Core Data “stack” inside unit tests, Bill Bumgarner has written about their experiences unit-testing Core Data itself and PlayTank have an article about introspecting the object tree in a managed object model. I’m not going to rehash any of that, though I will touch on bits and pieces.

In this post, I’m going to look at one of the patterns I’ve employed to create testable code in a Core Data application. I’m pretty sure that none of these patterns I’ll be discussing is novel, however this series has the usual dual-purpose intention of maybe helping out other developers hoping to improve the coverage of the unit tests in their Core Data apps, and certainly helping me out later when I’ve forgotten what I did and why ;-).

Pattern 1: remove the Core Data dependence. Taking the usual example of a Human Resources application, the code which determines the highest salary in any department cares about employees and their salaries. It does not care about NSManagedObject instances and their values for keys. So stop referring to them! Assuming the following initial, hypothetical code:

- (NSInteger)highestSalaryOfEmployees: (NSSet *)employees {
NSInteger highestSalary = -1;
for (NSManagedObject *employee in employees) {
NSInteger thisSalary = [[employee valueForKey: @"salary"] integerValue];
if (thisSalary > highestSalary) highestSalary = thisSalary;
}
//note that if the set's empty, I'll return -1
return highestSalary;
}

This is how this pattern works:

  1. Create NSManagedObject subclasses for the entities.
    @interface GLEmployee : NSManagedObject
    {}
    @property (nonatomic, retain) NSString *name;
    @property (nonatomic, retain) NSNumber *salary;
    @property (nonatomic, retain) GLDepartment *department;
    @end

    This step allows us to see that employees are objects (well, they are in many companies anyway) with a set of attributes. Additionally it allows us to use the compile-time checking for properties with the dot syntax, which isn’t available in KVC where we can use any old nonsense as they key name. So go ahead and do that!

    - (NSInteger)highestSalaryOfEmployees: (NSSet *)employees {
    NSInteger highestSalary = -1;
    for (GLEmployee *employee in employees) {
    NSInteger thisSalary = [employee.salary integerValue];
    if (thisSalary > highestSalary) highestSalary = thisSalary;
    }
    //note that if the set's empty, I'll return -1
    return highestSalary;
    }

  2. Abstract out the interface to a protocol.
    @protocol GLEmployeeInterface <NSObject>
    @property (nonatomic, retain) NSNumber *salary;
    @end

    Note that I’ve only added the salary to the protocol definition, as that’s the only property used by the code under test and the principle of YAGNI tells us not to add the other properties (yet). The protocol extends the NSObject protocol as a safety measure; lots of code expects objects which are subclasses of NSObject or adopt the protocol. And the corresponding change to the class definition:

    @interface GLEmployee : NSManagedObject <GLEmployeeInterface>
    {}
    ...
    @end

    Now our code can depend on that interface instead of a particular class:

    - (NSInteger)highestSalaryOfEmployees: (NSSet *)employees {
    NSInteger highestSalary = -1;
    for (id <GLEmployeeInterface> employee in employees) {
    NSInteger thisSalary = [employee.salary integerValue];
    if (thisSalary > highestSalary) highestSalary = thisSalary;
    }
    //note that if the set's empty, I'll return -1
    return highestSalary;
    }

  3. Create a non-Core Data “mock” employee
    Again, YAGNI tells us not to add anything which isn’t going to be used.
    @interface GLMockEmployee : NSObject <GLEmployeeInterface>
    {
    NSNumber *salary;
    }
    @property (nonatomic, retain) NSNumber *salary;
    @end

    @implementation MockEmployee
    @synthesize salary;
    @end

    Note that because I refactored the code under test to handle classes which conform to the GLEmployeeInterface protocol rather than any particular class, this mock employee object is just as good as the Core Data entity as far as that method is concerned, so you can write tests using that mock class without needing to rely on a Core Data stack in the test driver. You’ve also separated the logic (“I want to know what the highest salary is”) from the implementation of the model (Core Data).

OK, so now that you’ve written a bunch of tests to exercise that logic, it’s time to safely refactor that for(in) loop to an exciting block implementation :-).

Posted in cocoa, CoreData, objc, unittest | 2 Comments

CocoaHeads Swindon is this Monday!

The town of Swindon in the Kingsbridge hundred, Wiltshire is famous for two things. The first is the Wilts and Berks Canal, linking the Kennet and Avon at Trowbridge with the Thames at Abingdon. Authorised by act of parliament in 1775, the canal first passed through the town in 1804 and allowed an explosion in both the industrial and residential capacity of the hitherto quiet market cheaping.

The second is, of course, the local CocoaHeads chapter. Founded by act of Scotty in 2007, Swindon CocoaHeads quickly brought about a revolution in the teaching and discussion of Mac and iPhone development in the South-West, its influence being felt as far away as Swansea to the West and London to the East. Unlike the W&B canal, Swindon CocoaHeads is still thriving to this day. On Monday, 7th September at 20:00 there will be another of the chapter’s monthly meetings, in the Glue Pot pub near the train station. Here, Pieter Omvlee will be leading a talk on ImageKit, and the usual combination of beer and Cocoa chat will also be on show. As always, the CocoaHeads website contains the details.

Posted in cocoa, iPhone, macdevnet, Talk | Leave a comment