Making Cocoa the Outermost Layer

Teaser image

Chris Eidhof of objc.io put some experimental code on GitHub where quite a few Cocoa view components are contained by classes he owns himself. The AppDelegate is super instructive: Your Cocoa app needs an NSApplicationDelegate. But it doesn’t have to do anything except route events to the proper collaborators. Still it’s the first object we usually put logic in only to (hopefully) refactor it out later.

Continue reading …

Separate Read Model from Write Model to Support Complex Forms

One thing that repeatedly messes up the conceptual purity of a view model is figuring out which entity should be mutated upon user interaction. Part of this purity stems from the fact that a view model is best served as view data to stress that it doesn’t contain much (business) logic. Making the data mutable introduces a lot of problems figuring out what that view model really is.

Continue reading …

iOS View Architectures and VIPER Explained

There’s an excellent overview of MVC, MVP, MVVM, and VIPER in iOS with sample codes by Bohdan Orlov of Badoo I recommend you read.

There are two main takeaways:

  1. One of the commenters nailed it: any MV* variant focuses on architecting view components. Only VIPER takes the application as a whole into account. MVC by itself is an architectural pattern, but not an approach to app architecture in itself.
  2. A UIViewController belongs into the user interface layer and is, in fact, a composite view itself. That’s confusing at first because of the name. This insight will liberate you from thinking that a view controller is sufficient to glue data to UIKit components. There’s room for a whole application between these two.

The VIPER example is exceptionally good. It takes VIPER’s heritage of Clean Architecture and Hexagonal into account and defines the Interactor through an output port. In that way Bohdan’s sample code is more east-oriented and cleaner than what you’d usually find on the topic:

protocol GreetingProvider {
    func provideGreetingData()
}

protocol GreetingOutput: class {
    func receiveGreetingData(greetingData: GreetingData)
}

class GreetingInteractor : GreetingProvider {
    weak var output: GreetingOutput!

    func provideGreetingData() {
        let person = Person(firstName: "David", lastName: "Blaine") // usually comes from data access layer
        let subject = person.firstName + " " + person.lastName
        let greeting = GreetingData(greeting: "Hello", subject: subject)
        self.output.receiveGreetingData(greeting)
    }
}

Usually, you’d model provideGreetingData() as a function that returns the data to the caller. This will cause trouble in async processes of course.

You see in the full example that the amount of types seem to explode. Don’t be afraid of that as long as you can assign each type a specific responsibility. Then it won’t turn into the mess everyone seems to be afraid of.

Having used VIPER in apps myself, I see a problem with the names, though. XYZInteractor and XYZPresenter aren’t much better than XYZController in terms of expressiveness. On top of that, a concrete Presenter is always modelled to act as event handler, too. Don’t let this fool you into thinking you absolutely have to do this yourself – there’s always room to separate writing from reading operations, or event handling from view population.

Make Money Outside the Mac App Store

book cover

Today I’m proud to announce the release of my e-book Make Money Outside the Mac App Store!

Get it for $25 $19 until Dec 24th from my store!

Shaving off VAT and then again 30% for Apple for every purchase of your app in the Mac App Store can be madness: the only real benefit is that people know how to operate the store. But if you’re just starting to run your business, discoverability is hardly a feature.

Instead of drowning in the warehouse that the app store is, put your software in your own store. You have to build an audience anyway to get started. So stay in touch with them. Know your customers. And stop giving away 30% for a promise that doesn’t hold.

  • Save days of research and implement the techniques today
  • Copy & paste Swift 2.0 code to integrate into your app in <1 hour
  • Utilize in-app purchase of licenses for a higher conversion instantly
  • 2 fully functional sample applications, including a time-based trial app
  • Secure license code generation and verification included

Take a look at the details page for more info.

This book will save you hours of research and days of fiddling with SDKs. It shows you how to set up products for sale on FastSpring including automatic license code generation and then guides you through the process of adding license verification to your app.

Don’t need all the explanations? Just follow the setup steps and copy the code into your project and you’re ready to roll in half an hour!

I’m not affiliated with FastSpring. I just think their service is awesome.

Here’s what FastSpring’s CTO Mike Smith has to say about the book:

We appreciate Christian’s efforts in creating a guide that enables Mac developers to sell applications through FastSpring’s award-winning e-commerce platform. He has provided detailed instructions to help developers configure key elements of their online sales process. The spirit of community captured in his book reflects FastSpring’s mission to connect people globally in the digital economy.

I truly believe in the spirit of community and I believe you can make it as a developer without the App Store. This book is here to empower you so you don’t have to figure out all the scary details.

So many other indies rely on FastSpring, too, including:

  • Smile Software (TextExpander, PDFpen)
  • Realmac Software (Clear, RapidWeaver)
  • Tyler Hall (VirtualHostX)
  • Ironic Software (Yep, Leap)
  • Bohemian Coding (Sketch)
  • toketaWare (iThoughtsX)
  • well, and me, obviously :)

Get to know their stories from this book. Be inspired and take the leap.

Because I think it’s so worth your time as a Mac developer, get it for 25% off until Christmas when you buy from my store.

Yelp's Modular UITableViews

Yelp reuses a setup of modular table views across their huge app. A simple timeline entry can be composed of 5 cells, each with its own model representation. These cells are used to create various component setups. What I find most interesting is the combination of registering cells for reuse identifiers in one place and using reuseIdentifierForCellAtIndexPath in another.

Continue reading …

Configuration Objects: Delegate Initialization to a Parameter

The Builder design pattern is often overlooked, I find. Apart from plain builders, in Ruby I found that some us it like a configurator. You can use a configuration object in Swift in the for of block parameters, for example: This would make the internals of ComplexThing configuratable through the block. Instead of messing around with an instance of a ComplexThing, you can do atuff with the configurator which determines how the instance will look.

Continue reading …

Parameter Objects Simplify Your API Versions

I watched an AltConf about API design the other day. I cannot seem to find which talk it was, though. Anyware, the presenter talked about using parameter objects when the parameter list grows too long or is open for change in future versions. Parameter objects can change internally and evolve with the API. You can add or remove attributes, for example, while the API calls of old client code don’t have to change: they still pass the same type in. That makes framework updates a bit less painful because method signatures stay the same.

Continue reading …

Tips to Conquer Massive View Controllers

View Controllers should only be responsible for view lifecycle events, Marcus Zarra reminds us. That means they should populate views with data, and show and hide them – stuff like that. View controllers should not do the work of views.

While I like his overall advice, it contains a few problematic points:

  • Put Core Data out of the view controller. His solution to provide a single data source tied to a NSManagedObjectContext will not scale well as I’ve experienced. – Still, don’t tie it to the view controllers. That makes matters worse.
  • His definition of “business logic” is odd. Business logic is not reducible to I/O code. It’s not just about fetching data from a device and doing network requests – except when your app is a very, very simplistic display for data with CRUD operations. Business logic can exceed data-centric rules and entail a real domain with complex behavior without much imagination.
  • Views should be responsible for displaying data, agreed. Since validation problems will be presented to the user, validation error messages will be part of that data, too. But views should not validate. Validation rule objects (WWDC’14 talk) should be the strategies that do validation.

If we create an object to sit between the view and the view controller then we are creating unnecessary additional objects.

Where do presenters sit? Between view and and view controller – but they make it easier to read and extend the code. They’re hardly unnecessary.

I strongly believe that it’s impossible to give advice about how to code and architect something if the problem domain isn’t part of the example. Because everything depends on the problem space in the end.

Remember to take every advice with a grain of salt. Collect things like Marcus’ tips to obtain new tools, but don’t take the tool for the solution of modelling a program to solve real problems.

Ruby 2.3 Will Have Optional Chaining

Swift, C#, and Groovy had it – now Ruby 2.3 will get it, too: a “safe navigation operator”, or what we call “optional chaining”.

Instead of:

if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large

You can now write (with the beta):

if u&.profile&.thumbnails&.large

They didn’t use the ? because Ruby method names usually have a postfix question mark when they return a boolean; also, they will have a postfix bang when they mutate the receiver. This would’ve led to confusion.

Since Swift came out, I haven’t used Ruby a lot, really. I still use it for all my scripting needs, but coding real applications? Rarely. I really like strong typed languages for that: leaning onto the compiler for refactorings and such.

See the Ruby enhancement issue if you’re curious.

Jiggle GCD Queues to Find Problems

To debug my threading issues and help bring forth future problems, I have created a simmple object that slows the current queue down:

let IsRunningTests = NSClassFromString("XCTestCase") != nil

struct QueueJigglePoint {

    /// Randomly interfere with the thread.
    static func jiggle() {
    
        guard !IsRunningTests else { return }
    
        #if DEBUG
            usleep(2*1000000) // 2 seconds
        #endif
    }

}

I got this idea from Brett Schuchert on pages 188–90 of Uncle Bob’s Clean Code. A Handbook of Agile Software Craftsmanship. There, interference with traditional threading should randomly sleep, yield, or fall through. Enqueued blocks are a lot less volatile, so I only came up with sleeping.

Randomizing the sleep interval is up next. But a fixed number of 2–10 seconds helps find UI-blocking code already.

Just throw in a QueueJigglePoint.jiggle() in NSManagedObjectContext.performBlock executions, when dispatching async to the background, or when reading files, for example.

Modeling: From Structured Data Representation to Problem Domain

Teaser image

Recently, I was discussing adding a feature to an application which is about event creation and booking. The project manager has a strong database background and works on the schema himself. The schema is also his go-to tool to express changes in the features. But thinking about the real Domain in terms of objects revealed much, much more.

Continue reading …

Ideas to Solve Background Fetching and Saving Race Conditions with Core Data

I ran into problems with my Core Data Unit of Work/Transaction implementation the other day. I was not exercising good NSManagedObjectContext hygiene and end up with conflicts from time to time. Race conditions. Hate ‘em. The problem is that the parent–child setup of Core Data managed object contexts seems to work just fine for so-called “scratch pad” contexts: create a new child context, perform changes on in, then discard, or save to pass changes to the parent context.

Continue reading …

Productive Writer's Bundle Sale

website screenshot
The Productive Writer’s Bundle 2015

This year, the team of Texts, Brett and I teamed up to bring you the best minimal writing product bundle for the Mac. It’s designed to get you through NaNoWriMo: the accompanying guide tells you how to make the habit of writing stick and how to get most out of the apps.

The lineup of apps:

  • Texts for focused writing (even on Windows PCs!)
  • Marked for previewing and reviewing
  • Word Counter to increase your productivity
  • BONUS: iThoughts X (coupon for 30% off) to plan the plot with Mind Maps
  • BONUS: Minimal Writing on the Mac guide

I use these apps myself to write, so creating this bundle was a no-brainer and a very exciting experience – oh was I busy! – but more on that later.

The Productive Writer’s Bundle is a sexy deal at more than 50% off, for $25 instead of $60 – for every author, be it novelist or non-fiction technical writer.

Grab it now. And tell your friends.

Word Counter Now with File Monitoring

Teaser image

The Word Counter received a huge update this week. It now allows you to monitor files. That means you can create a record of your project progress. The usual words-per-hour meter will tell you how well you perform, while the file monitor can tell you how far you’ve come.

screenshot of the monitoring view
The new monitoring view with my current writing projects

I’m excited to finally release this update. I think it’ll help motivate a lot of people to make progress and marvel at their current achievements.

Up next is a graphical representation of all this, because visualizing helps to see progress, obviously.

If you have trouble downloading the update, please get a fresh download from the website. This will probably affect a lot of people. I’m very sorry for the inconvenience!

Don't Build on El Capitan Without Checking App Transport Security

I got burned this week. Pretty bad. I shipped a small bugfix release for my Mac app Word Counter a couple of days ago to prepare for the “big one” coming this week. Naturally, I built that version on my El Capitan dev machine. I pushed the update to my server. Updates using Sparkle worked. – But now users of that version cannot ever update to the next version. Because I haven’t thought about ATS.

Continue reading …

NSOpenPanel's and NSSavePanel's Block-Based API is Superior

I got angry at NSOpenPanel the other day for visually blocking NSAlerts, and for staying in the way when the debugger hits a breakpoint. Silly me, I used ye olde runModal. When you use the block-based API of NSSavePanel or its decendant NSOpenPanel, all of a sudden they will display on top, but only per application. Also, alerts seem to have a higher display level in these cases.

Continue reading …

Small Helper Objects Take You Far

Teaser image

Integrating new functionality is fun. But revisiting 18-months old code isn’t. Back then I created a protocol InvokesWindows to define methods like -showPreferencesWindow which I imported in the menu bar controller to show the preferences when the user selects a pop-up menu item. But I didn’t actually delegate to any instance of InvokesWindows. I used NSApp. (Insert facepalm here.)

Continue reading …

How I Solve the Unexpected Error Handling User Experience Problem

Teaser image

For the upcoming Word Counter upgrade, I developed a new feature module in isolation. The outcome is very interesting, as I am including it as a Swift module, that is as a real framework, into the existing app. I need some more time to write about the resulting architecture, but I found the module boundary to be really helpful. Today, though, I want to share my ErrorHandling code.

Continue reading …

Make Custom Debug Build Configurations Play Nicely With CocoaPods

To test the Word Counter during development, I have long used a special build target. But that doesn’t scale well if all I want is change a preprocessor macro to switch from file-based to in memory storage, for example. I’ve never played around with build configurations in Xcode. They work well with Schemes, though, and setting up a build configuration and a scheme is much less overhead than maintaining a custom target.

Continue reading …

Transactions and Rolling Back Changes in Core Data with UnitOfWork

The Unit of Work pattern is a code equivalent to database transactions: when it completes, changes are persisted; when something fails, changes are rolled back. That’s handy to perform a set of changes and have them saved. Sooner or later during app development using Core Data, you may ask: when should I save? When is the best point in time?

Continue reading …

Leave a Rating for Move! app on MacUpdate

Move!, my personal favorite productivity and health enhancement app (and, apparently, my own creation), is now available on MacUpdate. Check it out for free if you haven’t already.

Please leave a quick rating on MacUpdate so other people know how good you feel, now that you take regular breaks from work.

If you feel super-awesome today, feel free to leave a short review, too.

Your support helps me continue my work. Every star counts! ⭐️⭐️⭐️⭐️⭐️

Thank you!

Screenshot of Moive!
Now look who’s caught me looking at reviews.

Revisiting the Core Data + Domain Model Architecture

It happens that just yesterday I read about architecture smells in code. Among the examples was “subclasses don’t redefine methods”. In my post about Core Data and expressive domains earlier this week, I did just that: create a Egg subclass of CoreDataEgg to inherit CoreDataEgg’s behavior. That’s not what abstraction to superclasses is meant to do.

Continue reading …

Move! – Work Break Timer Now Ready for El Capitan

Teaser image

The Apple Watch is all the hype since it gently reminds you to stand up and move regularly. That’s a very good thing. A gentle reminder won’t cut it for me. That’s why I created a solution which jumps right into my face.

Look at the project page of Move!.

It features responsive timers: when you don’t touch your input devices, the clock will not start to tick. Only when you sit down and work will the timer start and make you stand up soon.

Move! is now ready for El Capitan. The upcoming OS X update can come!

Swift Protocol Extensions as Mixins – And How Do You Test That?

I found a very useful distinction by Matthijs Hollemans to grasp what protocol extensions in Swift 2 can be: instead of interfaces, they are traits or even mixins. At the same time, I want to raise awareness for misuse: just because behavior is mixed-in doesn’t mean it’s additional behavior. The code may live in another file, but its functionality can still clutter your objects.

Continue reading …

Make Money with Mac Apps Outside the MAS: E-Book Prerelease, Need Feedback

I have written a book about releasing apps outside the Mac App Store. It comes with two fully working sample applications to cover checkout from within the app, licensing, and locking the app after a trial period.

It’s called:

Make Money Outside the Mac App Store: How to Sell Your Mac App with FastSpring, Secure It With License Codes Against Piracy, and Offer Time-Based Trial Downloads.

I’d love to have feedback on this.

If you want to help out, just shoot me a line at: hi@christiantietze.de

Thanks!

P.S.: The secret Leanpub page is here.

Using Guard in Unit Tests

I have just discovered how cool the new guard statement is to keep unit tests lean and shallow – avoiding if-let nesting, that is. Consider this test case: There are two optionals I have to deal with. That’s why I throw in assertions to cover problems. I don’t want to assert anything new here, though: the test helper soleFile() is valdiated in another test case already. But I need some kind of failure in case the Core Data test case goes nuts.

Continue reading …

How to Change the Detail of a UISplitViewController in the Background

A UISplitViewController has a master and a detail view controller. When the selected item is deleted and the detail is visible, you can perform a segue. If the detail is not visible, performing a segue to change the detail will present it. I didn’t want that. There are two cases where you will want to change the detail although it’s not visible:

Continue reading …

Dismissing a Modally Presented Scene on Both iPad and iPhones Using Unwind Segues

UISplitViewController is the way to go when you want to make your iOS app universal without much hassle and can model the scenes in terms of master/detail. While getting Calendar Paste ready for the upcoming iOS 9 release, I discovered that using UISplitViewController across devices is one thing, while Storyboard segues are another.

Continue reading …

How to Create Flexible Components with Two Levels of Service Objects

Again I was reminded about the value of service objects to encapsulate sequences in two places: the Domain, where business rules are kept, and in client code, where database management and transactions play a role. This distinction helps create clean code and deliver flexible components. I am building a feature for the Word Counter in a separate “library” project until everything runs smoothly. Then I’ll integrate the code into the main application. Since I consider this to be some kind of library, I thought I wouldn’t need many service objects, but I was wrong.

Continue reading …

What is CLEAN Code?

Writing clean code makes your life better in the long term, and I find it’s more fun initially. According to Bernstein, CLEAN is an acronym:

  • Cohesive
  • Loosely Coupled
  • Encapsulated
  • Assertive
  • Non-Redundant

His book “Beyond Legacy Code. Nine Practices to Extend the Life (and Value) of Your Software” seems to be a good read. Not through, yet.1

  1. Affiliate link; I get a small kickback from the vendor if you buy from my link but it won’t cost you anything. 

Move! – Work Break Timer Release

Teaser image

During summer, I have created a work break timer called Move! which really works. It gets in your way, it cannot be postponed. I created it to make me get up and stretch and do something else for a couple of minutes every half hour.

Sascha and I plan to add exercise instructions later. Right now, we’re happy to have a tool which forces us to get up every now and then and get healthy. (Backed by research, mind you!)

Try it.

It will get on your nerves. Continue to take breaks when it tells you to.

You’ll hate it.

You’ll yell at it.

But it will make you feel better in the afternoon.

Do yourself a favor and try to do some diagonal stretches or a healthy 1-minute routine.

Download Move! on its dedicated page now and experience it for yourself.

Where Instead of Using Functional Bind, I Create an Expressive Model

Teaser image

The other day, I wrote a post about bind() and the >>= operator and how it can help chain function calls together. The example was a bit too contrived and making it fit the requirements left us with really bad code. I came up with an even better implementation: use plain Swift objects and express your intent carefully.

Continue reading …

Cut-Out Animation of a Table View Cell Into the Next Scene

I haven’t dabbled with animation a lot. So I was pretty surprised that there’s a method on UIView called snapshotViewAfterScreenUpdate which creates a static duplicate which you can use for animations easily.

I found this in a AltConf talk by Marin Todorov called “Power Up Your Animations!”. There, he does … well, I don’t know what it’s called, or else I would’ve picked a better title. See for yourself.

Here’s a crappy screen capture of the animation in his talk in action:

animation
Visually cut-out the cell by copying it, then animate a scene transition while it hovers on top, then move it to top.

His code is on GitHub, where you can check out how the TableCellAnimatior works. I think this is a very amazing, yet subtle animation. I find it unbelievable how easy it is to implement.

It seems I have no reason to fear animation in the future.

How to Write Pragmatic, Testable Singletons in Swift

Singletons have their use. I use two Singletons regularly in my projects: a DomainPublisher and a ServiceLocator. The latter is a registry of service objects which is global so the service objects don’t have to be. For practical use, most Singletons are overcomplicated or overly restrictive. Here’s how I suggest you implement Singletons in your apps:

Continue reading …

Refactoring Legacy Code: Replace Free Function in Tests, Even Swift's Own Functions

Teaser image

Refactoring Legacy Code is hard. There are a few safe refactorings you can do with caution. But most chirurgical cuts require you to put the code in a test harness first to guard against regression. With C and Swift, you can create free functions as part of your app. To verify your objects use that function, you need to find a way to insert a test double.

Continue reading …

Support the Word Counter With a Review

Teaser image

I’m working hard on the Word Counter. By October, I’m going to finish a really big feature: file and folder monitoring. It’s a pretty tough ride till then to get it done.

Since the Word Counter is not on the Mac App Store, please show your support and leave a ★★★★★ rating on MacUpdate.

You don’t have to write a full review in order to leave a rating. Just click the five stars at the very top of the page – but a review is much appreciated, of course!

As always: if you experience any hiccups on Yosemite or El Capitan, please tell me so I can fix the bugs.

“Exploring Mac App Development” Updated for Swift 2.0 + Coupon to Save 50%

Teaser image

It’s a good time to update my book for Swift 2: guard clauses improve readability, and do-try-catch error handling shows problem points. Protocol extensions are huge, but I had no use for them in the sample code, yet. The update is live now. If you haven’t bought the book in the past, grab it until August 1st to save more than 50%: use the coupon Swift2Yay. The coupon is good for 10 copies, so be quick.

Continue reading …

Clean Coding is a Programming Misnomer for a Software Engineering Principle

Teaser image

I found a cute info-graphic on how to become an iOS developer by John Kim. This study guide contains a passage with a very interesting distinction between programming and engineering. Thanks to it, I found out a detail about what it means to write “clean code.”

Citing from the graphic:

Programming is like building the bridge. You need to know how to use the tools to get your end result. In this way, you need to know the programming language to build your “bridge”

Software engineering is like knowing how to design a bridge. You need to know the proven industry design rules to make a long lasting and reliable “bridge”. In this way you need to learn software engineering to design great software

Learning the Syntax and grammar of a programming language is pretty straight foward [sic!]

Understanding software engineering is the hard part about becoming an iOS developer

Learn BOTH but focus on Software Engieering [sic!]

Software engineering is about the design principles. It’s the necessary condition to plan the components of object-oriented projects like those for iOS and Mac. It is required to write clean code.

Programming itself is about API knowledge, understanding the language grammar and the like.

Of course we write clean code, but we’re able to write it only because we’re able to make a clean design up in the first place. So there’s not much clean coding, but a lot more clean design.

Protocol Madness: Comparing Apples to Oranges from the Vantage Point of Fruit

Teaser image

Brent Simmons starts with Swift. And just as I, he struggles with value types, protocols, and generics: once a protocol references another or has a dependency on Self, you cannot use it as a type constraint or placeholder for all descending objects. You either have to use generics to expose a variant for each concrete type, or you re-write the protocol. There’s no equivalent to the way Objective-C did this: something like id<TheProtocol> just doesn’t exist. Swift is stricter. So how do you deal with that?

Continue reading …

How to Write Unit Tests for Storyboard-based Buttons in Swift

Teaser image

I’m writing unit tests for my Storyboard-based view controllers. Button interaction can be tested in view automation tests, but that’s slow, and it’s complicated, and it’s not even necessary for most cases. To write unit tests instead of UIAutomation tests for buttons, you test multiple things. Here are the tests.

Continue reading …

Freemium won't solve your problems magically

Teaser image

Freemium is said to be a popular way out of the iOS App Store underground. Make your app freemium and skyrocket your downloads. Then sell cool stuff from within the app to unlock more features or buy expendable contents and services.

This doesn’t work for all things on the market, of course.

Shuveb Hussain wrote about his own freemium experiments and that he considers it a failure in his case.

Why did Shuveb’s app make less money with freemium than with a paid-up-front sales model? That’s hard to find out without more experiments, but unlike in science, I guess you can only have that many trials in the App Store before users stop to trust you.

Shuveb himself said multiple times that his app is really really niche-specific. His freemium model allows people to convert one article to Kindle per day for free; more cost money. Maybe his users need no more than one article per day, maybe often times even less. That’s possible but hard to say without analytics about usage patterns from within the app.

Even with app analytics, how can you find out usage patterns if people know they have only one shot per day and probably don’t open the app more often than that?

You can only compare to data from the less limited intro phase. Do users stop opening the app regularly after they converted their first 3 articles?

growing money
Photo credit: Euro Money in Pots by Images Money. License: CC-BY 2.0

Read Stuart Hall’s experiments with the vastly more successful 7-Minutes workout app. He switched to In-App Purchases and people loved it. He found folks liked buying features less than buying additional content. I try to keep that in mind because it makes sense, but then again, I’m probably biased towards the good story.

Finding out how to make money with iOS apps is pretty hard. Actually making money is easier if you have a huge following of people you can market to. It’s easier with a network of bloggers and journalists. It’s easy when your app doesn’t actually suck.

Well, of course it’s easier if it isn’t hard.

I believe in value of the craft. I have to in order to stay sane. But crafting alone doesn’t feed hungry mouths. It merely keeps me happy. We need a market, and we need to reach it, and we need to deliver timely. There’s a lot of uncertainty and pressure. Making apps freemium from the get-go might not solve any of our problems. We have to think twice about it, you and I and all the other indie app devs. And maybe hope for a niche of professionals who are willing to pay more. (Which is the other popular promise how to become successful.)

Generics in Objective-C

Objective-C got generics! No more collection classes just for the sake of guarding against invalid elements!

I used custom collection classes a lot for the Word Counter to let the compiler help me prevent mistakes. Swift generics were a godsend for that kind of safety. Now, Objective-C can achieve similar awesomeness.

It can look like this:

@interface Wheel : NSObject
@property (nonatomic, strong) UIColor *color;
@end

@interface Vehicle : NSObject
@property (nonatomic, copy) NSArray<Wheel *> *wheels;
@end

Now the compiler will warn (!) you if you misuse it:

Vehicle *car = [[Vehicle alloc] init];
[car.wheels addObject:@"NSString is of the wrong type"];

Great news, since if you didn’t spend a lot of time creating custom collection types yourself, now at last can you ensure array element type consistency. Makes your code cleaner and more reliable.

Be Cautious with Try-Catch for error handling in Swift 2.0

Teaser image

Throwing exceptions and being able to catch them is awesome news. Then there are cases which can be handled with try-catch technically, but shouldn’t. Think about this: in what cases could you make use of that? And what are the consequences for your work? For example, Erica Sadun points out that accessing array indexes out of bounds as a subscript will still crash the app since you can’t catch that kind of exception (yet).

Continue reading …

Test doubles for Core Data managed objects might not work as expected

You don’t have to learn anything new if you work with Core Data in Swift. It’s a pain to use NSManagedObject directly, so you better work with custom subclasses all the time. Unboxing optional NSNumbers is just too cumbersome. There are caveats you should be aware of, though: Swift’s static typing makes it a bit harder to write test doubles for managed objects.

Continue reading …

Swift Extensions and Information Hiding

Andrew Bancroft tested and analyzed the behavior of extensions in Swift. While his findings aren’t utterly surprising, having them summed up in this nicely done article certainly helps.

In a nutshell:

  • extensions in the same file as their source can access even privat members (attributes and methods, that is)
  • extensions in different files can access internal and public members – but only if they are in the same module
  • if extensions are in a different module, they merely have access to public members
  • classes with public or internal visibility on themselves expose their members as internal by default
  • classes with private visibility on themselves expose their members as private
  • extensions themselves don’t have to be public for public members to work (unlike classes)

This has consequences for your tests: they reside in a separate module, so they can only access public members of your classes.

If you extend classes from static libraries, the same holds true. Different module, only public accessors.

Success and Error Callbacks in Objective-C: a Refactoring

I’m refactoring code of Calendar Paste 2 some more. Since I like what I learned using Swift so much, one of today’s changes was about making a view controller method do less by factoring object creation and error handling into its collaborators. The resulting code handles far less of the action involved. Instead, it delegates the action to a new command-like object. And instead of querying an event template for data and assembling an actual event with start and end dates, it delegates event creation to the template itself. Tell, Don’t Ask saved the day.

Continue reading …

Book Updates for Swift 1.2

I have just updates the book Exploring Mac App Development Strategies to Swift 1.2. A few sections were expanded, a few paragraphs rewritten – but the big update is still underway. It’s due this summer, and then I’ll consider the book feature-complete. Until then, check out the current deal for Creating Multi-Process Mac Applications, which is available at a discount right now since it’s an early release version.

Continue reading …

Functional Programming in Swift (YouTube Videos)

Teaser image

After the latest change in my diet, I eat a lot more often throughout the day and try to spend the time watching educational talks to make use of my time. Functional programming seems to not only be all the hype – its concepts seem to reach mainstream thinking, too. Here’s a collection of talks you might find worth your while.

If you got some useful talks, share them in the comments!

Event Publisher Revision 1

I have imported my latest event publishing code into the Word Counter. Since the DomainEventType enum didn’t provide much value besides obtaining a notification name, I decided to get rid of it and obtain a name by another means.

In the current iteration (see the Gist), the event protocol reveals a static eventName. I also removed the duplicated notification factory from concrete events:

import Foundation
  
public typealias UserInfo = [NSObject : AnyObject]
  
public protocol DomainEvent {
    class var eventName: String { get }
  
    init(userInfo: UserInfo)
    func userInfo() -> UserInfo
}
  
public func notification<T: DomainEvent>(event: T) -> NSNotification {
    return NSNotification(name: T.eventName, object: nil, userInfo: event.userInfo())
}

It’s weird that I have to write notification<T: DomainEvent>(event: T) to access static properties of the event type. notification(event: DomainEvent) doesn’t work as of Swift 1.1., because “Accessing members of protocol type value ‘DomainEvent.Type’ is unimplemented”.

In a similar vein, a method like this doesn’t satisfy the generics requirement:

func foo(event: DomainEvent) {
    let notification = notification(event)
    // ...
}

But this does:

func foo<T: DomainEvent>(event: T) {
    let notification = notification(event)
    // ...
}

Mixing protocols and generics makes me wonder where the problem lies, but hey, it does work this way, although generics pose a slight performance penalty to protocols if I remember the WWDC talks correctly.

Painless Event Delivery With a Custom Publish-Subscribe Infrastructure

Teaser image

In my apps, I have used a custom event delivery mechanism on top of NSNotificationCenter with great success: I send a lot more events and consequently decouple parts of my code more easily. Putting your own objects around the Cocoa foundation can help use them more often. I want to show you how my EventPublisher works, and why custom event types make me send a lot more events than when I only had NSNotifications.

Continue reading …

Save Your Butt in Unit Tests With Shallow Reaching

I assume you do write tests. To test system boundaries, you have to find out whether methods are called. Usually, people reach out for mocks to verify behavior.

If you use a lot of mocks, though, the tests can reveal high coupling in your code: either you have to mock objects multiple levels deep, which is a sign of too much knowledge about how the collaborating objects work, or you have to mock lots of objects one level deep. The latter can be acceptable when you test a components which is some kind of coordinator. The former, though, is never to be accepted. Use the feedback of these hard-to-write tests to make your code simpler.

That’s what the Law of Demeter is for. While “law” is way too strict, its principle is sound: strive to call methods on the objects you have direct access to, but avoid calling methods on objects which you obtain through another method call in the first place.

For example, the following violates the principle:

func violateThePrinciple(aCollaborator: Collaborator) {
    let aStranger = aCollaborator.obtainFriend() // this is okay so far
    aStranger.doSomething() // this is not, because it's 2nd level
}

You can get by through providing facade methods:

func respectThePrinciple(aCollaborator: Collaborator) {
    aCollaborator.doSomething()
}

extension Collaborator {
    func doSomething() {
        self.friend.doSomething()
    }
}

In your unit tests, you can add a Collaborator mock to verify the calls and then you’re good to go. No multiple levels of mock objects and stubs. You may call this “shallow reaching” (opposed to “deep reaching”), although no one else calls it that.

That’s the Law of Demeter in a nutshell: only talk to friends which you know through properties or parameters, but don’t talk to strangers which you get to know through the return values of your friends’ methods. You never know what to expect.

Zettelkasten Posts Moved

Since we started the Zettelkasten blog, it became weirder and weirder to keep the old posts here. I found the split among domains unfortunate.

Today, I’ve moved all Zettelkasten-related posts to the project blog at Zettelkasten.de. The old addresses won’t change, and your comments have persisted, too.

Thanks for visiting this blog, and thanks for caring about what I write! If you’re still interested in personal information management, head over to the new place. If you’re into programming, though, stay here.

VIPER iOS App Architecture Approach

Teaser image
VIPER
VIPER, illustrated. Picture credit: Jeff Gilbert, Conrad Stoll, and Lin Zagorski of Mutual Mobile, used with permission.

Ryan Quan of Brigade Engineering has published an article about using the VIPER iOS app software architecture. Their write-up is really good: message passing is illustrated with code samples – and they even use neat box graphs!

I use a VIPER-like approach in my apps, too, and I’d like to invite you to try it for yourself. VIPER is inspired by Clean Architecture and Hexagonal.

In a nutshell, you decouple the view controllers from event handling from data management. You introduce so-called “Wireframes” to set up a module or “stack” of objects to display a view controller with certain data. The Wireframes set up everything once. Afterwards, event handlers take over, called “Presenters”. They perform transitions between scenes. View controllers do not much more than setting up the view and reacting to IBActions.

This will make maintaining code easier because the view controllers are finally put on a diet. Figuring out how data has to flow differently takes some getting used to. I’m going to write about this in a future post.

Split Commands and Informational Return Values Apart Using Events

When you reason about objects in your system and their means of communication, you can differentiate between three messaging flavors according to Mathias Verraes: imperative, interrogatory, and informational messages. Before we can talk about informational messages and their value, let’s recap the other two and see what the difference is, because them calling for being extracted is not easy to spot.

Continue reading …

Going Beyond Guard Clauses in Swift

Teaser image

Erica Sadun brought up a topic which is bugging me for some time already. It’s how Swift encourages you to handle optionals. It’s related to handling exceptions, which I covered earlier. Either you use if-let to unwrap them implicitly and do all the stuff inside the nested code block, or you end up with code which is a lot wordier than I’d like it to be.

Continue reading …

Functional Error Handling in Swift Without Exceptions

In Swift, there’s no exception handling or throwing. If you can’t use exceptions for control flow like you would in Java, what else are you going to do if you (a) write library code which executes a failing subroutine, and (b) you find unwrapping optionals too cumbersome? I played with the thought of keeping Swift code clean, avoiding the use of optionals, while maintaining their intent to communicate failing operations.

Continue reading …

Thinking in Terms of Functional Programming Encourages Clean Factoring of Code

Chris Eidhof provided an excellent example for creating a mini Swift networking library. It executes simple requests and can be extended to work with JSON (or XML, if you must) without any change. The accompanying talk is worth watching, too. You should check it out to see well-factored Swift code in action. It’s a great example.

Continue reading …

How John Sonmez Helped Me Streamline This Blog

Teaser image

I’m going to change things here a little bit in the upcoming weeks. Recently, I found out what I want to do with this blog. John Sonmez of Simple Programmer is offering a free three-week e-mail course for starting to blog as a software developer. I subscribed to check out what other developers on the web do, and I have read his 6 e-mails and followed some of his advice. One particular e-mails made me think about my projects, what they mean to me, and how they relate to each other.

Continue reading …

How to Resolve Word Counter Update Issues

Teaser image

Users have reported update problems after they purchased the Word Counter for Mac.

I am aware of this issue. The easiest fix is to download the latest version (.zip, 2.3 MB) yourself manually.

The version you got from the store cannot recognize more recent versions as valid, so it rejects the update. Maybe I can find a way to fix this on my side, soon. I pushed an update to the store already.

This is very unfortunate, and I’m very sorry for the trouble this has caused.

All the best to you,
– Christian

Subscribe to My New Mailing List

I have a Zettelkasten project newsletter for a few years already, and it was featured on this site as I wrote about the topic.

Since my endeavors on this worklog/blog have shifted, I think it’s the right moment to offer a non-Zettelkasten newsletter for the folks interested in my projects, the programming books, and the software I develop.

The new project newsletter will be my premier place for project announcements and software beta invitations. A lot of you have helped already make the Word Counter better. There’ll be lots of opportunities to test software for free in the future. There’s a bunch of stuff in the making.

Apart from project updates, I’ll provide a convenient list of posts I have published on all my project websites since the previous issue so you don’t have to collect these, too.

Thanks for your support and for reading this blog! If you want to stay up to date and benefit from a much closer contact, sign up now.

Storyboard Segues VS Tell Don't Ask Principle

UIStoryboardSegues are a blessing to add rudimentary navigation between view controllers in iOS projects. User interaction can trigger segues without any code. That’s all good and well to move back and forth between mostly static scenes in your Storyboard. Passing data around is not so easy, though, without making things more complicated.

Continue reading …