Saturday, September 28, 2013

Cocoapods - ARGV - Returns Options as a Hash, OCMock only for Tests target.

Tonight I actually made my cocoapods objc port use cocoapods. Most of the point of this adventure is for me to deeply learn cocoapods. I initially wanted to replace some manually written stubs in my first ARGV test with OCMock, but it OCMock doesn't support stubbing -[NSObject description], so I didn't actually need it. I imagine I'll need OCMock at some point, and it was also a good exercise in learning how to setup cocoapods dependencies only for specific targets, so I left it in.
I also tried implementing the "returns options as a hash" spec, but ran out of time. Ben Chatelain suggested I use FSArgumentParser:
but I don't think that's going to work. However, FSArgumentParser depends upon CoreParse, and that looks like it'll work out great. I'll probably use FSArgumentParser as an example of how to use CoreParse for my purposes, so I think Ben's suggestion will pay many dividends. I love knowing smart people.

Friday, September 27, 2013

Cocoapods adventures

We've started using Cocoapods at work, and it seems like a really great system. However, it is written in ruby, and I hypothesize that it would get more participation from the community if it was written in Objective-C. Also, since Cocoapods is a specification as well as a system, it would benefit from a separate (though in this case not clean-room) implementation. Thus, I'm going to rewrite Cocoapods in Objective-C and blog about my journey along the way.
Thankfully, Cocoapods looks pretty modular, and it looks like it has good tests. I'm starting with CLAide, which is Cocoapods' command-line aide. This has RSpec tests, which I know nothing about, but I can generally figure out what they're doing just by reading the text.
Tonight, I just wanted to start something. I wasn't too concerned about crazy progress. I simply cloned CLAide and figured out how to run the existing RSpec tests. I found the .travis.yml file with a script command that looked promising, so I tried running that, and installed required gems (bundler, rspec) until it worked.
Next, I just converted the first two tests in the first spec (argv_spec.rb). I'm doing at least one commit for each test I convert. Also, I'm keeping all this work on a separate branch. Eventually, I'll just have a parallel Foundation command-line tool project that I'll keep up to date.
Tomorrow, I'll tackle the first real piece of parsing necessary. Hopefully, I'll have ARGV converted by Sunday night.

Saturday, June 15, 2013

All the smart kids are writing blog posts about exceptions

Since all the smart kids are writing blog posts about exceptions, I figure if I write one, I might be considered smart by association. :)

I favor automation in all things. I will happily supply metadata with my code that will allow it to be automatically verified to be correct, or at least more correct than it could be without the metadata. This colors my viewpoint on exceptions.

This all started because of Craig Buchek's tweet:
I prefer code that enumerates exactly what it will return and how it might fail via the type system. I used to prefer checked exceptions everywhere for this, but I've since changed to just returning a either a good return value or an error.
Old Java:
class Foo {
  Foo foo() throws FooException {
    if (Math.random() < .5) {
      throw new FooException();
    } else {
      return new Foo();
    }
  }
  Foo bar(Foo foo) throws FooException {
    if (Math.random() < .5) {
      throw new FooException();
    } else {
      return foo.foo();
    }
  }
  String baz() throws BazException {
    try {
      Foo foo = foo();
      Foo barFoo = bar(foo);
      return "I ran the gauntlet with " + barFoo;
    } catch (FooException f) {
      throw new BazException(f);
    }
  }
}

With this code, you can capture all your handling for common errors in one place, and because FooException is a checked exception, the compiler will happily tell you if you forget to handle your error cases. Yay!

However, errors are data just like everything else, and they don't need to be shunted off into a separate world. One might assume that if we remove exceptions, we'll end up with a lot of annoying if checks:
class Foo {
  Either<Foo, FooException> foo() {
    if (Math.random() < .5) {
      return new Either<>(new FooException());
    } else {
      return new Either<>(Foo);
    }
  }
  Either<Foo, FooException> bar(Foo foo) throws FooException {
    if (Math.random() < .5) {
      return new Either<>(new FooException());
    } else {
      return foo.foo();
    }
  }
  Either<String, FooException> baz() throws BazException {
    Either<Foo, FooException> eitherFooOrFooException = foo();
    if (eitherFooOrFooException.left()) {
      Either<Foo, FooException> eitherBarFooOrFooException = bar(eitherFooOrFooException.left());
      if (eitherBarFooOrFooException.left()) {
        return "I ran the gauntlet with " + eitherBarFooOrFooException.left();
      } else {
        return new Either<>(new BazException(eitherBarFooOrFooException.right()));
      }
    } else {
      return new Either<>(new BazException(eitherFooOrFooException.right()));
    }
  }
}

It doesn't have to be that way. Jessica Kerr describes how in detail. However, Java idioms and language limitations do make these functional styles difficult. So, if you're in Java-land, I won't look down upon you for sticking with Exceptions, as long as they're checked.

Saturday, December 1, 2012

Objective-C Does Not Belong Outside of Mobile

The power of Objective-C comes from its tight and nearly seamless integration with C. The power of C comes from its focus on efficiency and performance and its quasi-portability. Both of these qualities are essential for mobile development. Mobile devices run on a number of different platforms with different binary types (Android uses ELF, while iOS uses Mach-O) and generally have tight clock and memory constraints. Given these compromises, C is a great choice.

However, C doesn't support object-oriented niceties that were fashionable 10-15 years ago, and it doesn't support functional niceties that are en vogue now. Objective-C does an passable job at the former is trying to get better at support for the latter with the help of ReactiveCocoa and friends.

So, given that Objective-C minimally satisfies the requirements of a modern language, should we extend it to the web? I don't think so. The web doesn't operate under the same CPU and memory constraints, so we can use some of that power to make developers more efficient. In cases where bottlenecks occur, most programming environments still support C development. Objective-C may make sense there. However, most developers aren't building Facebook, and Facebook has even figured out a way to make its code more efficient while harnessing the power of its army of highly skilled PHP developers.

Kevin Lawler makes a case for Objective-C on the server. I'll break down my disagreements with his article below. I'll use Java as a counterexample since it is currently the dominant player and is widely deadpanned as being an awful language. If Objective-C can't beat Java, it doesn't stand a chance against ruby, python, javascript, clojure, scala, or any other server-side cult hits.

Objective-C is not a joy:

In the past few years, quietly, almost invisibly, Apple has transformed its Objective-C language into the best language available. I have been working with Objective-C since the release of the iPhone App Store in 2008. In that time Objective-C has evolved from a clunky, boilerplate-heavy language, into a tight, efficient joy. It is an amazing tool. Anything that I would not write in C I would want to write in Objective-C, were support available.
No. Objective-C is not an efficient use of developer time, nor is it a joy. There is still a ton of boilerplate present. I'm sure there are many other things I hate about Objective-C the language, but these are just a few things I came up with off the top of my head.
  • I must declare both an @interface and @implementation for every class.
  • The compiler doesn't support circular references, you must forward declare classes and protocols that are circularly referenced with @class and @protocol.
  • There is no support for namespaces, leading to names like kBluetoothAMPManagerCreatePhysicalLinkResponseAMPDisconnectedPhysicalLinkRequestReceived
  • There are no private methods. There is no way to be sure that a subclass won't accidentally override one of my internal methods simply by reusing one of my names.
  • No type variables (generics)
  • Can't add nil to Foundation collections
  • No support for inner classes
  • It is a superset of C, so everything you hate about C goes here too.

A paragraph full of fail:

To understand the opportunity facing Objective-C it will help to summarize where Java fails. The original promise of Java was that an application written once would compile and deploy on any architecture. Ignoring that this is false, web shops don't use Java for this reason. Platform inconsistency is an issue for almost no one, and it was never an issue to port correct C/C++ code, universal compatibility being the original promise of C as well. This promise however spurred the creation of the JVM, which was Java's first mistake. The JVM is a nonsense abstraction over the assembly and UNIX system layer. Now code runs through an additional layer, which can be slow, and system interactions must be translated through an otherwise pointless, just-for-this-purpose Java API. In the ideal case, this API replicates the entirety of the UNIX system layer in Java-ese, obscuring any helpful C idioms or UNIX-system knowledge in the process, and creating a pointless set of new knowledge to understand. In the less than ideal case, the API fails to implement system-level functionality and creates a barrier between the application and the machine.
 So much is wrong with this paragraph.
Ignoring that this is false, web shops don't use Java for this reason.
There are certainly edge cases, but this is far from false. Java is very much write-once run everywhere. More importantly, it is compile once, link and run everywhere. I'll grant you that some Java libraries have crazy mavenized builds that can take way too long to run, but that isn't Java's fault. Code that you write in Java will compile the same way on any machine and run basically the same way on any other machine, regardless of endianness, instruction width, or operation system. Web shops depend on this to easily consume libraries from all over the Java ecosystem. I invite Mr. Lawler to look at the amount of platform specific code in the average Apache Jakarta project. I'll bet it is effectively zero.
Platform inconsistency is an issue for almost no one, and it was never an issue to port correct C/C++ code, universal compatibility being the original promise of C as well.
I'm hardly a C badass, but I'm pretty good at Java. I'm not at all confident in my ability to write correct platform independent C code. Thankfully, I only target iOS, and I only build with xcode, just like every other iOS developer out there. Nearly all iOS developers build with Clang, and most are on one of a few key versions. I can't imagine trying to build a reusable library that would compile and link with all the different C/C++ compilers/linkers and run on nearly any system.

Even if we ignore the need to write universally compatible code, I would have to invest great amounts of time in consuming any library that wasn't written specifically for my platform. If I wanted to use Apache commons-codec, but it was written on 32-bit Windows, I'd be very skeptical about consuming it on 64-bit Mac without a thorough review. I have no such concern about Java. I can't believe it is 2012, and I have to make that argument.
This promise however spurred the creation of the JVM, which was Java's first mistake. The JVM is a nonsense abstraction over the assembly and UNIX system layer.
No. The JVM is a portable UNIX system layer that runs everywhere. The JVM brought UNIX to windows, and its portable bytecode has enabled an amazing ecosystem of languages, most of which has the power to interoperate.
Now code runs through an additional layer, which can be slow, and system interactions must be translated through an otherwise pointless, just-for-this-purpose Java API.
I guess Mr. Lawler has never heard of the Hotspot JVM's amazing inlining technologies in its JIT compiler. Also, he links to a stackoverflow answer that basically says Java is not slow at all, though the answer does list some downsides with respect to memory and startup time, both of which aren't issues for the web.

A few more nits to pick:

Garbage collection makes execution (and memory usage) unpredictable. You cannot postpone garbage collection forever. The more critical the execution, the more you want to postpone garbage collection, but the longer you postpone garbage collection, the more of a problem it will eventually be. This is a disaster for applications that need to scale.
There is truth here, but Azul's Zing basically blows it all away.
Oracle now owns Java and is a hostile entity. Java is done. Its future as a product is finished.
Although Oracle decimated the JCP, they have been a terrific steward of Java for features. They actually shipped Java 7, which greatly improved performance and includes many new features (including lots of missing UNIX APIs).
As an aside, tying any new language to the Oracle JVM is destined to be a mistake, for reasons previously mentioned.
The JVM is a great place to run a new language. JRuby applications saw free performance gains of up to 30% just from moving from Java6 to Java7.
In practice, object-oriented programming lets large teams of competent programmers build usable software. The same is rarely said for functional languages. In cases where functional language applications do succeed, they are often treated as prototypes and rewritten.
I can point you to a whole army of people that would disagree with that. I know of 3 different companies just in St. Louis that build very big systems with functional platforms. Of course, this is only anecdotal evidence, but I'm sure functional languages are taking off if a small town like St. Louis has such a good showing. Of course, twitter famously uses functional languages for many things, including processing its massive logs.

The lines that caused me to write this blog post:

5. Xcode is an excellent IDE, with tolerably good git support
This line just killed me. Xcode is the biggest piece of shit modern IDE I've ever used. I outlined my hatred in a presentation I gave to Lamda Lounge. If Mr. Lawler thinks it is excellent, he's clearly never used Eclipse JDT or IntelliJ IDEA, and he's never been amazed at swapping hot code at runtime with JRebel. He must not have ever wanted to use a structural code formatter, either. I'm sure he doesn't care about creating plugins or modifying the tools he uses. I doubt he wants a transparent bug reporting system.
IDE auto-completion works wonderfully.
No, it doesn't. I just barely works. If there are any compilation errors in the class, the autocomplete fails.   It stupidly suggests methods from all over the various C APIs that I've never used and I doubt would ever be applicable to my code. It never prioritizes local variables or methods that I most often use. "NSS" doesn't complete to "NSString", it completes to "NSStream". "NSLo" becomes "NSLoadedClasses".
The library import process is less tedious than in Java.
I think Mr. Lawler is trolling me. Xcode has no auto-import at all. In Eclipse, if I type "Set", "import java.util.Set;" is automatically added at the top. I would love this feature in Xcode. If I want a library in Xcode, I have to use the mouse to navigate through 5 modal operations.

Still Good For Mobile

Again, mobile development operates under a different set of constraints. We need C on mobile, and we need a modern superset of C to build mobile applications. Objective-C is a decent choice. As I outlined above, it has warts, but they are tolerable given the constrained environment of mobile. Thanks for journeying with me on my insane screed.

Friday, July 6, 2012

Categorizing your radars

When you encounter a bug in Apple's iOS code, you need to report it. I was always confused about the Product against which I should report my bug. There are 3 categories that made sense to me:

  • Developer Tools
  • iPad SDK
  • iPhone SDK
Thankfully, former Apple Developer Evangelist @jury cleared it up for me:
Basically, use iPad SDK if you find it in the iPad Simulator/device, use iPhone SDK if you find it in the iPhone Simulator/device. Don't double-report the bug, indicate that it exists in multiple categories in the bug text.

Monday, June 18, 2012

Abstract Methods on Legacy Objects Using Categories

Let's say we have the following classes:


@interface HBAbstractLegacyNode : NSObject

@end

@interface HBChildNode : HBAbstractLegacyNode

@property (nonatomic, strong) NSString *childProperty;

@end

@interface HBParentNode : HBAbstractLegacyNode

@property (nonatomic, strong) NSString *parentProperty;

@end



If we want to add a template method onto HBAbstractLegacyNode, we ordinarily, just alter our classes thusly:


@interface HBAbstractLegacyNode : NSObject

- (void) templateMethod;
- (NSString *) abstractishMethod;

@end

@implementation HBAbstractLegacyNode

- (void) templateMethod {
  NSLog(@"templateMethod: %@", [self abstractishMethod]);
}

- (NSString *) abstractishMethod {
  [NSException raise:@"Override" format:@"%@ should override %@", NSStringFromClass(self), NSStringFromSelector(_cmd)];
  return nil;
}

@end

@implementation HBChildNode 

- (NSString *) abstractishMethod {
  return self.childProperty;
}

@end

@implementation HBParentNode 

- (NSString *) abstractishMethod {
  return self.parentProperty;
}

@end



But what if we're dealing with legacy code or a 3rd party library, and can't or don't want to modify our existing classes? Then, we can utilize categories to add methods, and use protocols to get some compile-time type safety.


@protocol HBOptionalAbstractish 

@optional
- (NSString *) abstractishMethod;

@end

@protocol HBAbstractish 

@required
- (NSString *) abstractishMethod;

@end

@interface HBAbstractLegacyNode(HBTemplate)

- (void) template;

@end

@interface HBParentNode(HBAbstractish)

@end

@interface HBChildNode(HBAbstractish)

@end

@implementation HBParentNode(HBAbstractish)

- (NSString *) abstractishMethod {
    return self.parentProperty;
}

@end

@implementation HBChildNode(HBAbstractish)

- (NSString *) abstractishMethod {
    return self.childProperty;
}

@end

@interface HBAbstractLegacyNode(HBOptionalAbstractish)

@end

@implementation HBAbstractLegacyNode(HBOptionalAbstractish)

@end

@implementation HBAbstractLegacyNode(HBConsumerCodeTemplate)

- (void) template {
    NSLog(@"template: %@", [self abstractishMethod]);
}

@end



We define two parallel protocols, one whose methods are optional, and one whose methods are required. Apple's Category Documentation says:
There’s no limit to the number of categories that you can add to a class, but each category name must be different, and each should declare and define a different set of methods.

Further restrictions exist (I can't find a link to Apple documentation beyond this stackoverflow answer, please help me find a link to real docs):

Although the Objective-C language currently allows you to use a category to override methods the class inherits, or even methods declared in the class interface, you are strongly discouraged from doing so. A category is not a substitute for a subclass. There are several significant shortcomings to using a category to override methods:
  • When a category overrides an inherited method, the method in the category can, as usual, invoke the inherited implementation via a message to super. However, if a category overrides a method that exists in the category's class, there is no way to invoke the original implementation.
  • A category cannot reliably override methods declared in another category of the same class.
    This issue is of particular significance because many of the Cocoa classes are implemented using categories. A framework-defined method you try to override may itself have been implemented in a category, and so which implementation takes precedence is not defined.
  • The very presence of some category methods may cause behavior changes across all frameworks. For example, if you override the windowWillClose: delegate method in a category on NSObject, all window delegates in your program then respond using the category method; the behavior of all your instances of NSWindow may change. Categories you add on a framework class may cause mysterious changes in behavior and lead to crashes.

I interpret the above to mean we should not override methods from categories. Thus, we define the optional protocol who we will implement with a category on our superclass, HBAbstractLegacyNode. Then, we'll implement the required protocol on each of our subclasses.

Unfortunately, we don't have complete compile-time type safety. We must manually ensure that the methods in HBAbstractish and HBOptionalAbstractish have matching signatures, and we must manually ensure that we create category implementations for each new subclass we create. Thus, we don't get complete fidelity with abstract methods you find in Java, but we get close.

Declaration and implementation order matter to ensure that the compiler doesn't think subclasses have inherited an implementation from their superclass. The protocol declarations must come first, but the subclass interface and implementations must come before the superclass'. If the superclass' interface comes before the subclass' implementation, the compiler will think the subclass already has an implementation from the superclass and will not warn us if we haven't provided an implementation. Since the superclass implements the optional protocol and we don't provide any methods in its implementation, the superclass actually provides nothing to its subclasses.

This is a lot of work to get a few helpful hints from the compiler, but when you have an enormous codebase spanning hundreds of files, all these checks (in concert with unit tests), go a long way towards stopping stupid errors.

Thursday, February 9, 2012

iOS 5.0 MKMapView (MapKit MapView) Edge Cases

The following are notes from my adventures implementing complex custom callouts in an MKMapView on iOS 5.0.

  • The selected MKAnnotationView is brought to the front of the group.
  • When the selected MKAnnotationView is deselected, other undefined annotations may appear in front.
  • Calling -[MKMapView selectAnnotation:animated:] on an annotation with a disabled MKAnnotationView will not select the MKAnnotationView. 
    • The MKMapView will not call -[MKMapViewDelegate mapView:didSelectAnnotationView:].
  • If MKAnnotationViews overlap and one is selected, touching the selected one will select an unselected one.  Since custom callouts must be implemented as ordinary MKAnnotationViews, you must disable all MKAnnotationViews behind a callout MKAnnotationView if you want the user to be able to interact with UIControls inside your callout MKAnnotationView
  • Any UIControls in your MKAnnotationView must exist within your MKAnnotationView's frame. Otherwise, when the user attempts to touch them, the map will think the user touched outside the MKAnnotationView and deselect your MKAnnotationView.
  • You may change the frame of your MKAnnotationView after the MKMapView calls -[MKMapViewDelegate mapView:viewForAnnotation:] and -[MKMapViewDelegate mapView:didAddAnnotationViews:].  However, you can't change the -[MKAnnotationView centerOffset].  So, if you change the frame size, it needs to grow equally in all directions.
    • When you don't grow the MKAnnotationView's frame evenly, it will appear to look fine at first, but when you zoom the map, it will snap to its old centerOffset.