This is an article I originally wrote for the brazilian online magazine DevMedia’s Mobile Magazine. This first part is the article’s introduction, so seat back and relax. Soon I’ll post the second - and final - part with a tutorial to the Apple like documentation generator appledoc.

“In the agile programming environment, using methodologies such as SCRUM, Agile and Lean, we can’t always document our sources. After all, pragmatics as we developers are, why would we lose time if the documentation won’t be compiled, won’t do any difference in the code’s performance and demands a considerable slice of our time? But despite all that, the lack of documentation hurts. A lot.

Who’s familiarised, knows that in the ultra accelerated rhythm of startups, where everything is at the top of the list, there’s not always time to apply some of the good programming technics that aren’t crucial to the sanity and speed of the code. Oftenly, there’s no time to formally test classes and methods because of the virtually null due time that is given. It’s easy to find developers awake all night in hackatons to successfully deliver that key feature that will make “the whole difference”. Test? Document? Review? There’s so much to do and so little time!

That’s the reality of many young developers who enter this ultra competitive environment searching for the dream of running their own companies. The responsibilty of satisfying potential investors, the pressure for deploys and the client’s needs frequently obfuscate technics that improve development and maintenance experiences, but that are not considered primordial to the construction of an application. How often didn’t I went back to an undocumented code done less than two months before and thought “what the flock does this loop do?” or “why, on earth, is this class here and not there?” Of course, when those lines of code were written, everything made perfect sense, but the moment those ifs and fors went out of the conscious mind, their meaning were long gone. After all, quoting the chinese saying: “the ink is better than memory”.

So let us document. It doesn’t hurt, doesn’t make you fat and isn’t illegal. Actually, documenting is like eating vegetables: no one really likes it, but we do it hopping that, in the end, it’s worth the result. But unlike the vegetables, it’s proved that documenting helps. Contrary to the common thought, the time spent documenting a day’s work is reasonably irrelevant and the benefit in return is definitely worthy. With practice and experience, no more than 30 minutes can be lost documenting everything that was made in a whole day. That way, the developer stays focused in his activity and doesn’t deviates doing other stuff that draws his attention or stand in his way of writing the best possible algorithm. Therefore, don’t wait until the end of the week, when the work pile up, part of the features were already forgotten and we’re all dying to that ice-cold friday-night-beer. Personally, I recommend documenting in the end of the day. In my case, it’s always the last thing I do before leaving, because everything is still fresh in memory and the amount of code produced in one day doesn’t compare to what’s done in one week. If that’s not enough, I realised that I do a final unconscious revision before the final commit when I’m passing by the code documenting it.

A well documented code is good for everybody. What would be of us without the independent frameworks, packages and repositories used daily if they weren’t documented, or even had a bad documentation? Even senior programmers, frequently, return to Apple’s documentation to a better understanding of Cocoa’s classes. Whether consulting a less used protocol, or lower level functions to manage sockets, threads or semaphores. Nobody can remember everything, so don’t try it, you’re not an elephant. It’s not rare to find developers who use the documentation as a last resource to understanding some tool. This line of thought makes sense if we think that we want everything to be as explained as possible so we don’t lose any time trying to interpretate any possible use, when trying to comprehend some feature. But we must never forget that even when visiting forums, asking more experienced developers or reading articles in blogs, EVERYTHING had a documentation as basis. Well, even this article wouldn’t exist if wasn’t for appledoc’s documentation.

Documenting - or at least commenting - source codes is fundamental to the intelligibility of the code. Implementing these technics with developers that never done it, oftenly is seen with prejudice and suspicion that are common to the staunch and stubborn nature of young programmers. I must confess that I didn’t wanted to document when people first told me to. Moreover, because of it’s so unusual syntax, it’s interesting to verbalize what’s developed in ObjC to ease it’s lecture, specially by more unexperienced programmers.

As time goes by, with the expansion of the startup, the pressure and need of code documentation is felt. Contrary to many programming languages - such as Java with it’s hideous GUI Javadoc - Objective-C doesn’t have an “official” documentation generator. In our quest to find a differentiated framework, which could make us feel as if we were really making difference, we found the excellent appledoc that, using code comments à la Javadoc, generates Apple like documentation, with a docset automagically installed in XCode, static HTML sources which can be uploaded to a cloud (vide  NSStringMask which uses appledoc) and an interface identical to Cocoa’s.

Among appledoc)’s already described advantages, are also the documentation parsing through code comments, wich allow the developer to consult the documentation without the need of opening a new window, since everything is in the code. The integration with XCode allows the visualisation of tooltips with quick access to the documentation by simply holding the Option key and clicking a method or class. Moreover, by “compiling” appledoc) in your documented project, the library’s docset is already imported to your Organizer. Simple or not? But, undoubtedly, appledoc)’s main advantage is it’s interface that’s identical to Apple’s documentation. I think it’s very unlikely that there’s any ObjC developer that has never read Cocoa’s documentation, be the one embedded on XCode or the on in Apples developers portal. By reusing the known model, it terminates the problem of having to familiarise to a new layout.”

Soon I’ll be posting the second part with a tutorial.

Fork me on GitHub

When developing, we often come across code we’ve seen hundreds of times that we just copy and paste from project to project. Sometimes it’s so banal that it’s not worth trying to improve, change or even modularize it. Ctrl-C + Ctrl-V may be the cheapest and fastest solution, ergo, the best.

This is the kind of situation we see when masks must be applied to text fields such as Social Security Numbers (SSN), Telephones, Zip Codes, and so on. Those awful few dozens of lines we copy from one textField:shouldChangeCharactersInRange:replacementString: to the other. It never changes because it works. There’s no need to improve it. It’s always the same. But I’ve got tired of it. That nasty code that, in a well structured class, can be as a mole in a beautiful woman’s face.

A few days ago I got some spare time and I started working on something I though could come handy. So how do you simplify and generalise this problem that every developer has to face at least once? Easy! Regex! Wait.. You sure it’s easy? I’ll tell you, it wasn’t easy, but we’re talking about patterns in varying occasions and, as I visualised it, regex is the best, simplest and most “approachable” solution. I mean, everybody knows a little bit of regex.

While modelling, I wanted to make it as simple and as clean as possible, therefore, for now, there are only two classes, and only one method you’ll really use, but you can read the complete documentation. From now on, I’ll present a superficial approach to introduce this small library.

Fork the Github Repo!

NSStringMask

The NSStringMask is the main class responsible for applying your masks to the NSStrings. Among it’s methods the only noteworthy is [NSStringMask maskString:withPattern:placeholder:].

It formats the given string based on the pattern you provide, filling the voids with the placeholder. It automatically creates an instance of NSRegularExpression with the option CaseInsensitive, so if you need a different option, you may use the alternate method which expects a regex instead of pattern.

There’s also an alternative method that receives no placeholder (same as nil), in this case, when the given string is shorter than expected, instead of applying the mask, the method will return a cleaned string having only the valid characters based on validCharactersForString:.

Important Note

Doesn’t matter if providing a pattern or an instance of regex, the regular expression must have capturing groups (parentheses). This is because the class understands that everything that is not within parentheses is part of the mask and must be interpreted as literal characters!

Suppose you’re formatting a SSN, whose regex pattern is \d{3}-\d{2}-\d{3}. If you provide that regex/pattern, nothing will be formatted because the class will think that \d{3} is part of the mask, and not 3 numbers that should go there.

The correct usage is: (\d{3})-(\d{2})-(\d{3})

// RIGHT:
NSString *result = [NSStringMask maskString:@"12345678" withPattern:@"(\d{3})-(\d{2})-(\d{3})"];
// result = @"123-45-678"

// WRONG:
NSString *result = [NSStringMask maskString:@"12345678" withPattern:@"\d{3}-\d{2}-\d{3}"];
// result = nil

Obs: If Xcode is showing a warning about unknown escape sequences, try adding double slashes (\\d)

UITextFieldMask

This is a subclass of UITextField, so you can set your nibs to use this class and automatically apply masks to your text fields.

Obviously, you must provide a mask to transform your strings, and it’s recommended that you do so when initialising your view or view controller. So you should set the text field’s mask inside viewDidLoad or awakeFromNib.

Suppose you have a view with an outlet to an UITextFieldMask named textFieldMask:

- (void)awakeFromNib
{
    NSStringMask *mask = [NSStringMask maskWithPattern:@"(\d+)"];

    textFieldMask.mask = mask;
    textFieldMask.delegate = self;
}

A question for you: what does that mask accepts?

Installation

You can install it from Cocoa Pods, or clone the project from the Github Repo and copy the files in the folder Classes.

Helpful stuff

I’ve also created this gist with some common patterns. Feel free to improve it!

Tired of having to find out where an exception occurred, that was only captured in the main()? Now I’m going to show you the best Xcode tip that no one talks about. Don’t ask me why.

These are the very few steps that will save your life and make your day better.

Creating an “Exception Breakpoint”

The first thing to do is to access the Breakpoint Navigator, which is the little breakpoint marker on the top of your Project Navigator. If you didn’t know, the Breakpoint Navigator show all your breakpoints in your project, where you can easily manage them. (Click on the image to see it bigger)

best-xcode-hint-1

Now that you’re in the Breakpoint Navigator, click on the little “+” button on the bottom left of the screen. A little dialog window will show up and choose the “Add Exception Breakpoint…” option.

best-xcode-hint-3

Then, the Xcode will ask you some information about the breakpoint you’re creating:

best-xcode-hint-4

  • Exception: There are three options: “All” to get all types of exceptions; “C++” to get only C++ exceptions; and “Objective-C” to get only ObjC exceptions. I like to leave it as “All”.
  • Break: Leave it as “On Throw”. This way, the execution will stop when your code throws an exception and not when it catches, which is the default on main().
  • Action: You can set some action to be performed when the breakpoint is reached like run an Apple Script, shell command and others. I’ve never used it.
  • Options: if you check this option, your code won’t stop when the breakpoint hits, making it useless. So leave it unchecked.

Congratulations! You’ve successfully created an Exception Breakpoint that will stop whenever something odd happens! Let’s try it out!

As an example I’ve created an empty array and tried to access the object at index 0, which doesn’t exists. This is what happened:

best-xcode-hint-5

Whoa! The Xcode stopped precisely where the problem was! Quite awesome, huh? But, sometimes, it’s not that easy to visualise what the problem really is, so if that’s happening to you, just hit “play”, and the code will keep executing as if your breakpoint doesn’t exists. What happens now, is the main() catching whatever exceptions that may happen.

So you can look at the console to see what the problem was:

best-xcode-hint-6

”-[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array”

Ta daa! I know it’s not perfect. It won’t get any signals (SIGABRT, SIGTRAP), flags or bad access kinds of witchcraft, but I think it’s super helpful and I think you guys should know.

SQLite sucks. I think everybody knows, but I had to say it. But, sometimes, we have no choice other than using it. Even though it’s horrible and we know we`ll be frustrated, once in a lifetime, SQLite may be the best choice. Wether developing a program with a tiny or fast persistence. Sure there are other alternatives that may suit you best, but the platform we’re using may not support it.

For instance, I’m currently working on an iPad app that will have a fairly big amount of data which must be available offline and it will have to be updated sometimes. The best solution we came with is a background server task wich will build an SQLite database populated with the most recent data and, when the user requests, the iPad will download the whole database, overwriting any existing ones.

I’m no DBA, but I don’t think anyone writes database creation scripts anymore. At least not for the usual CREATE TABLE, etc. I’m mostly a MySQL guy and, for a long time, I’ve been using MySQL Workbench to create my DB models and syncing with my existing database. It automatically creates everything that needs to be created and alter all tables that must be altered without losing any data (most of the time). It’s pretty good and I never had any problems with it.

Now, back to listing reasons why SQLite sucks (dude, you can’t add a constraint when altering a table!). As any platform/framework with no “official” team, SQLite depends on the community to increase it’s awesomeness. Therefore, as everybody knows SQLite is not awesome, no one really waste time developing a good administration tool for it. What may happen, is a company own a DB management program (such as Navicat) and something like this goes by:

- Hey, we're supporting MySQL, SQL Server, MongoDB, Cassandra, NoSQL and Postgree,
don't you think people will notice we're ignoring SQLite?

- God dammit *gasps*, add support to it too... but don't lose too much time with it!

Unfortunately, there are no really good tools to work with SQLite available. “Hey, what about Navicat?” It’s okay, but I found tons of bugs in the Mac version. If that’s not enough, are you really willing to pay to use a management tool for a free, open source database? But if you search deep enough - like the 3rd page of Google - there are also some weird stuff that appears such as SQLiteStudio (for Mac). When I see things I like that I think “why the hell would people lose time developing something for SQLite?” But hey, there are weirdos for everything, so I’d like to thank for the SQLiteStudio team for being strange enough to create it.

Even though it’s not the best tool ever, SQLiteStudio sure comes in handy and helps a lot, but it doesn’t solve the mentioned problem of modelling your SQLite database and not dealing with SQL scripts. So, searching for something that would fill this void I found this excellent script in Lua for MySQL Workbench that automagically generates the SQLite CREATE script from a model. It’s super easy to install and use. Just follow this steps:

  • Download the .lua script (duh!)
  • Click in the “Scripting” menu in MySQL Workbench.
  • Click “Install Plugin/Module”.
  • Choose the downloaded .lua script.
  • ???
  • Profit.

That’s it. Now, if you want to try, open a model, click the “Plugins” menu and under “Utilities” there must be an option named “Export SQLite CREATE Script” which may be the first one. Just click it and choose where to save the .sql script and execute it. Voilà! If you have any problems executing the generated script, you may need to comment the BEGIN; at the top and the COMMIT; at the bottom of the .sql script.

Super easy, isn’t it? Give it a try. Even if, like me, you hate SQLite. The plugin solves the modelling problem, but creates a new one, because you can’t ALTER an existing table since it only generates the CREATE script. But if that’s not a problem go for it and be happy. When I found it, life suddenly became joyful again.

“Once upon a time, there was a tiny invisible force named Luck. Everybody loved it and gave it gifts, hoping that, when needed, Luck would come for them. But Luck had a younger sibling called Bad Luck, who hated Luck with all it’s strength and always tried to be the opposite of Luck, because, while everybody smiled and cheered for Luck, no one liked when Bad Luck was around. People twisted their noses at Bad Luck and everybody blamed it for every bad thing that happened in their lives.”

This is that time of year when joy and happiness take over people. Some folks are going on vacations and we won’t see again for a while, and every single one of them, without exception, while saying goodbye, wish “happy holidays, and good luck!” If there’s one thing I can’t understand is this misconception people have on luck and bad luck. I see all those people on new year’s eve wearing white, jumping waves, and doing all kinds of foolishness hoping it “will bring them good luck” and I can’t understand.

Luck isn’t something you can “force” or hope to come. “Luck” is the name we give for a chain of events that, coincidentally, affect you in a good (luckily) or bad (unluckily) way. Let’s picture an hypothetical scenario: you’re riding a bike and, right before you cross another street, you hit a pedestrian. Was bad luck that put that asshole there, right? Now, what if, one second after you hit him, a car goes by at 60mph crossing the street you are at. Not so bad luck hitting that good citizen now, huh? So, although the result is the same, the denomination we give to that chain of events changed because of one single variable: some douchebag driving his car while talking on the phone. So, what was bad luck for you, became luck. But what about for that poor guy you hit? For him, independently of the result, he’s still pretty banged up, so he had bad luck. It didn’t randomly pointed at him and said “you, sir, are gonna get screwed!” It did just happened. Bad Luck. When you do something that goes badly and you knew the odds were against you, that’s not bad luck. It’s not the universe flipping you the finger and screaming “fuck you, Jimmywobble!” That’s stupidity. YOLO my ass!

I not always wear white on new year’s eve, but when I do, it’s not because I think it will bring me peace in the upcoming year. It’s because I want to get into the spirit of the party. Those thousands of people in white, happy, drunk and with the promise of better things to come are what drive me to join them and put on a white shirt.

But don’t think I’m crazy just yet. If I’m walking down the street and I see a ladder landing on a wall, of course I’ll pass around it. Not only I do not want anything to fall on my head, but hey, what if I’m wrong? Why would I bet against it when I don’t know if it will get angry and come back to bite me in the ass?

So, in this year’s ending, I wish that every single little incident that happens to you in 2013 may be chained to good fortune. I hope that slam you’ll give with your pinky finger in your table helps you find that earring you’re looking for for three years. Or that tongue bite you’ll have may lead you into meeting some super hot nurse.

So I wish you well in the new year. I hope you all the best.

And good luck.