Archive for the ‘Cocoa Coding’ Category

CryptoQuip Solver in Swift

Tuesday, February 3rd, 2015

Swift

OK, I've spent several hours with Swift, and it's pretty close to Ruby, but it's not the same in that the String is still a class, and that means that it doesn't have the duality that a string in Ruby - or clojure - has. This makes a lot of the functions in the CryptoQuip solver a lot harder.

Little things, too - like finding the distinct characters in a String. In clojure it's easy:

  (count (distinct "rabbit"))
  => 5

and even ruby it's nearly as easy:

  "rabbit".chars.to_a.uniq.count
  => 5

but in Swift, it's nasty:

  func distinct(list: [Character]) -> [Character]  {
    var buff = Dictionary<Character, Character>()
    for x in list {
      buff[x] = x
    }
    return buff.keys.array
  }
 
  let src = Array("rabbit")
  distinct(src).count

I did find a StackOverflow idea that does it, but it's a function that basically builds up a new list by adding one element at a time, and then checking before each add that the new element doesn't already exist in the collection. Since both these collections are Arrays, this is a linear search over and over and over again, and it's a mess.

I'm sure Swift has a ton of nice features, and it's quoted as faster than ObjC - which is nice, but issues like this make me realize it's a 1.x language and that the builders haven't had the time to go into the same use-cases that they have for other code bases, and fill in all these kinds of features that will make it a lot easier to write more complex systems.

For now, I'm content to hold off on more Swift work. It's just not where I'd like it to be.

UPDATE: I added in the function that I wrote, and it works, but Holy Cow! it's a mess. You can't easily make it one call:

  distinct(Array("rabbit")).count

because you have to worry about the mutability of the Array, and that causes warnings in the code... it's just not ready for all the things you need to do. Soon, hopefully.

Swift Dictionaries are Always Value Types

Tuesday, February 3rd, 2015

Swift

More reading in The Swift Programming Language and I've come to the part about Arrays and Dictionaries. Specifically, a dictionary is treated as a Valu e, and that means that it's copied on every assignment and on all function or method calls. The significance of this, to me, is profound. One of the singularly most useful data structures for a coder is the dictionary (the other is the array), and to find out that passing around a dictionary makes a copy on each method call and on each assignment.

In the CryptoQuip codebase, we create a map of all the known words - where the key is the pattern of the word, and the value is an array of all known words with that pattern. As we run through the list of words (a file), we calculate it's pattern, and then add it to the array in the dictionary for that pattern. In clojure, we really compute all the patterns for the words, and then group them by their patterns.

We then pass this dictionary around to make it simple to find the possible words that a cypher text word could be. If the docs are as they have been written:

Whenever you assign a Dictionary instance to a constant or variable, or pass a Dictionary instance as an argument to a function or method call, the dictionary is copied at the point that the assignment or call takes place.

yet they also try to say this isn't an issue:

The descriptions below refer to the “copying” of arrays, dictionaries, strings, and other values. Where copying is mentioned, the behavior you see in your code will always be as if a copy took place. However, Swift only performs an actual copy behind the scenes when it is absolutely necessary to do so. Swift manages all value copying to ensure optimal performance, and you should not avoid assignment to try to preempt this optimization.

Sadly, StackOverflow isn't a lot of help, and this includes talking to someone in the Swift Language group in Apple. The advice appears to be: Wrap it in a class.

The reason being that all Classes are pass-by-reference as opposed to pass-by-value. While this certainly can solve the problem, it makes something that should be very simple a lot harder. I can see how to do this, and should we move ahead with the CryptoQuip solver in Swift, it can be done, but it seems like a hack.

Kinda seeing some of the cracks in the Swift language... not ideal, but it is what it is.

Swift Structures are Always Pass-by-Value

Tuesday, February 3rd, 2015

Swift

I've been reading The Swift Programming Language this morning just to stay sharp, and because I've read several accounts of where Swift out performs ObjC, and the ruby-like nature of Swift means that it might be a lot faster to code up. So I was reading more...

What I found was pretty surprising about the differences between Structures and Classes - Structures are always copied when they are passed around in the code. This means that there is no way to pass-by-reference a struct to a function or method, and this will certainly modify where they can be used.

As a counter-point, in C++, classes and structs are basically the same thing. There are very minor differences, at best, and yet here in Swift, it's a fundamental difference that they chose to implement, as opposed to had to implement, and that tells me that there's something they see in Structures that they don't see for classes.

Not quite sure what that is, but immutability could certainly be one thing - passing by value allows the value(s) to be modified, but the caller's values are never touched. There might also be something in the NSPoint structures as well - something where they are looking at very simple data elements with no methods on them. Yet this means you can't have a function that modifies a passed-in structure.

Very interesting. Not sure where they are going with this, but it's something to look out for.

Restarted the Old CryptoQuip Solver

Monday, November 10th, 2014

xcode.jpg

This morning, my old friend Bret poked me with a stick to get me moving, and I fired up Xcode 6.1 and loaded up my old CryptoQuip solver, and gave it a run. The results brought a smile to my face - again:

  2014-11-10 08:43:42.536 CryptoQuip[87664:8603115] Solving puzzle: 'Fict O
       ncc bivteclnbklzn O lcpji ukl pt vzglcddp' where t=n
  2014-11-10 08:43:42.572 CryptoQuip[87664:8603115] Solution found: 'When I
       see thunderstorms I reach for an umbrella'

and the total run was only 36 msec. Very nice!

Then I decided to convert it to ARC because I know iOS requires ARC, and it should be even faster - right? I mean it's not doing the retain and release, so it should be even faster!

So I converted it to ARC, and removed all the retain and release and autorelease, and rebuilt it and re-ran it:

  2014-11-10 12:30:32.582 CryptoQuip[89789:8710573] Solving puzzle: 'Fict O
       ncc bivteclnbklzn O lcpji ukl pt vzglcddp' where t=n
  2014-11-10 12:30:32.640 CryptoQuip[89789:8710573] Solution found: 'When I
       see thunderstorms I reach for an umbrella'

So with ARC, it's taking 58 msec - that's a real increase. I had to run it several times to make sure that I was really measuring it properly. But there it was... as plain as day - 58 msec. Wow. ARC isn't cheap.

And as I started to think about it, it made sense - at least I came up with a plausible explanation: What if the retain/release version was using the standard Autorelease Pool. Then it wouldn't really hassle with deallocation in the runtime - it'd wait until the work was done to run the collector. However, ARC would see what needed to be done and then do it as it wouldn't wait for the pool to clean up. In that case, all the creation and destruction would come at a cost: Time.

In the end, it doesn't really matter - we have to use ARC for iOS, and it's not horrible for performance, but it does mean that I'm going to want to be careful as we move forward with this to not create all the temporary objects.

Flakey Docs… Flakey People… Dangerous Waters

Tuesday, October 28th, 2014

Danger

I've been working with an old friend on a project he brought to me about two years ago. There have been several cycles of work here - some really worked well, others not so much. But the current crop of code is about creating an iPad app for this third-party RESTful API. It's for UK midwives - and it's tracking the health and vital stats of the mothers and the babies - and it's a good thing to do as it helps out the people getting health care to the villages in the UK. Good goal.

The problem is that the API that I'm supposed to be writing to is really not well documented at all, and then it's got a really odd way of doing OAuth, and then making subsequent calls is not easy, and in all, it looks like it's been built by someone that really has no idea whatsoever of how to make a good, solid, reliable API. But maybe it's just the docs - who knows?

Well, today I've found out that it's not just the docs - they are bad, but it's the API as well because the docs are incomplete, and when I get a return value it's not what the docs say, so it's not even tracking the old, horrible docs. Additionally, my friend said he worked out how to make the calls by digging into the FORM values returned by the authentication call (yeah, makes no sense to me either), and when he tried it again a week later, the parameters have changed so that it no longer worked.

So in order to make this work we're scraping a web FORM, and it's so dynamic that it's going to change within a week? Yikes! That's all kinds of warning flags to me. Now I'm not trying to be a snob, and there are certainly plenty of issues with professionals doing this, but I can't remember such a really bad interface for a service. It's almost like it doesn't exist - as if the web site is all they have, and there's no plans at all for a decent RESTful API.

That makes a lot more sense than the things I'm seeing.

My friend is asking me if we want to fix this for this guy - and I can't honestly remember a time when that really worked. I'm not saying that it can't - I'm saying that in my life, I can't remember ever seeing it actually work. The singular boss would have to give up a lot of control on the tech side of things. He'd also have to give up a lot of the money he's making on this in order to compensate people capable of really making this a professional API.

On the up-side, he could then sell access to the API to people wanting to build apps on it - like he's attempting to do to us. But in it's current state, there's no way in the world I'd be willing to pay a dime for this - it isn't professional, and it exudes no trust.

I'm not sure what will happen, but I know sirens when I hear them...

Nice Singleton in Obj-C

Monday, October 27th, 2014

xcode.jpg

As part of this project I'm working on with a friend, I ran into the fact that in iOS development, Apple really doesn't allow the same level of control with custom objects that you can have with OS X development. For instance, it's very common in OS X development to have a controller class written in code and then instantiated in the xib, and wired up. It saves a lot of needless code of wiring up things, that's brittle and not really pushing the value of the app. My friends and I always called this Nib-ware, after the original NeXTSTEP Interface Builder files.

But what seems to be far more common in iOS is the idea of singletons. The key to making a good singleton is, of course, making sure that if you want only one, you get only one. And that usually means locking, or Compare and Swap - which is illegal with Automatic Reference Counting (ARC) code as it can't know if you got the swap or not. So when I found a simple way to make a singleton in Obj-C, I loved it's simplicity and beauty.

The header is simple enough:

  /*!
   This class method is the singleton of the PKBClient for the entire app.
   The first call to this method will create the singleton and initialize
   it for all uses. All state for the connection to the back-end will be
   stored in this one instance.
   */
  + (id) sharedClient;

and the implementation is just lovely:

  + (id) sharedClient {
      static PKBClient*	shared = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
          shared = [[self alloc] init];
      });
      return shared;
  }

So simple... a static value and then a simple block to initialize it, but the magic is in the dispatch_once - that's really exceptional. Sure, clojure has this, and a lot of other languages do, but this is the first time I've seen it in a C/C++/Obj-C language, and it makes so many things so much easier.

It's nice to work with good tools.

Finding the Joy in Life Again

Wednesday, October 22nd, 2014

Great News

I honestly would have put money on the fact that this would not have happened today. Big money.

I'm sitting on the bus riding to work, and I realize that I'm pretty happy without a pain-causing personal relationship in my life. That was a wow! moment. I've been separated for about 2 years, and the divorce is in the works, but I would have bet real money I'd feel horrible for the rest of my natural life. But today... on the bus... for a few minutes... I didn't.

That was huge for me. Huge.

Then I'm in work, updating a few postings with the results of the tests I'd done overnight, and I'm back into the swing of posting like I used to. It's been a long two years, but I'm back to writing about what I'm doing, and it's really helping. I'm feeling like I'm enjoying myself again.

This, too, was huge for me.

I don't expect this to last all day... but the fact that I have felt this way tells me that I need to keep doing what I'm doing - keep moving forward, and then maybe this will come again. And maybe when it comes again, it'll last longer. Maybe.

Xcode 4.6 is Out

Tuesday, January 29th, 2013

xcode.jpg

This morning I saw that Xcode 4.6 was out, and so I had to get it for my laptop. It included an update to the command line tools, as you'd expect, and the release notes indicate that they have pulled in all the Cx11 additions for C++, which - to me, is a great win. This includes the move semantics which makes a lot of the code I've written just a while lot more memory efficient - sweet!

There are also updated to the rest of the tools, and I was thinking, as I was updating just now, that Xcode has been my very favorite development environment of all time. It's just wonderful. Complex, yes. Hard to find things, certainly. But in the end, an amazingly powerful tool.

Charging What You’re Worth

Thursday, September 27th, 2012

GottaWonder.jpg

This morning I saw this on Daring Fireball, and it reminded me of the recent conversation I've had with a guy that contracted me to do some work for a Bank and said that it'd be worth $25k to him. So I did it. It took me about 2 weeks, but it was a lot of fun getting back into OS X coding that I didn't mind the time.

I actually made it more flexible than he/they needed. I could sync up and down data between multiple devices and it always makes sure to send minimal packets of information. It's not Rocket Science, but it's nice, and I'm really proud of it. I put it up on a private repo on GitHub and let him see it.

He wanted to use it for something else, and when he asked how much that was worth, I said: "$25k".

"What? You said it'd only take a weekend to make the customizations I asked for."

"Yes, but that's not the point… it's the value the code represents."

I just wish I'd had this quote from Picasso to reference him. I have it now.

"Five thousand dollars," the artist replied.

"B-b-but, what?" the woman sputtered. "How could you want so much money for this picture? It only took you a second to draw it!"

To which Picasso responded, "Madame, it took me my entire life."

The Death of Imperative Programming

Thursday, September 13th, 2012

I got a note from my manager, a link to this article and the words:

Found something that might stir you up

and sure enough, it did.

I can certainly understand that the rise of the functional languages is going to effect the traditional uses of imperative languages. Certainly for a lot of the uses - I'll even say the majority of cases, performance isn't an issue, and functional languages have the benefit of immutability and therefore a lot less error-prone. While developing in a functional language is vastly difference than an imperative one, there are still reasons to learn the functional approach, and make use of immutable data types - even in imperative languages.

But to think that imperative languages are going to die?

Yeah… No. Not gonna happen anytime soon.

Functional languages - even the most mature ones suffer from the garbage collection problem. If you're going to be creating immutable objects and doing anything with them, you're going to be creating new ones all the time. Kinda goes without saying. And this is where they all suffer.

Java is great, save the GC pauses. Erlang too, with it's smaller GC pauses, but they are still there.

For the rest of my life, to be sure, there are going to be a need for developers that are capable of doing the "hard stuff" - regardless of how many improvements the functional languages make.

Performance is going to matter.