How to Keep Photos Private on iPhone – A Step by Step Guide

We all have private photos we want to keep away from prying eyes.

KEYBOX not only keeps your photos private by requiring a login, it encrypts your photos using AES-256, the encryption algorithm used throughout the eCommerce industry. So if your iPhone is stolen the chances of the criminal ever gaining access to your photos is almost zero.

How to add a photo in KEYBOX

Photos can be added to any KEYBOX secret but let’s assume you want to create a photo collection.

 

Login to KEYBOX using your login password.

If the login succeeds you will be taken to the TOP screen.

 

 

 

 

 

 

 

 

From the TOP screen tap the All Secrets icon.

This will take you to the All Secrets screen shown here. Tap the + button in the top-right corner.

You’ll now be taken to the Add screen.

 

 

 

 

 

 

Usually the basic type of new secrets is “Custom”.

You want “Photo” so tap the basic type cell.

This will take you to the Basic Type selection screen.

 

 

 

 

 

 

From here select “Photos” (at the very bottom of the list).

Doing so brings you back to the Add screen.

 

 

 

 

 

 

 

Now 3 “Photo / Image” fields have been added. Tap the top one.

This will take you to the photo screen.

 

 

 

 

 

 

 

In the bottom left corner is an action button. Tap it.

 

 

 

 

 

 

 

 

A menu will appear.

If you want to select the photo from your camera roll select “Choose from camera roll”. Remember to delete the photo from the camera roll later if you use KEYBOX to safeguard it! If you just want to take a photo now select “Take a photo”.

 

 

 

 

 

Once you’ve chosen the image you want to safeguard tap the Done button in the top-right corner.

 

 

 

 

 

 

 

The photo has been given a unique ID which is now visible from the Add screen. Next, and at a minimum give the secret a name and tap the Save button.

 

 

 

 

 

 

 

You’ve now added a private photo to KEYBOX! It really is this easy!

Post to Twitter

Eye Candy: Levitating Girl Natsumi Hayashi

I don’t often visit Reddit but when I do I look for gems like this…

http://www.geekologie.com/2011/08/eye-candy-levitating-girl-natsumi-hayash.php Natsumi Hayashi, managing to vacuum the floor without tracking dirt with her feet.

Natsumi photographed here is incredibly talented.  She not only photographs these images herself but also maintains her normal facial composure and somehow manages to not let her hair or skirt flutter in the slightest!

It’s hard to believe she doesn’t use a high-speed shutter for these and actually jumps upwards of a 100 times to get just the right shot.  I hope her knees hold out.

Post to Twitter

KEYBOX In-Depth Feature at AppAdvice!

The fine folks at AppAdvice have an in-depth feature of KEYBOX and have posted lots of screenshots for all to see!

Clinton Ferreira, the reviewer, does a great job describing how to use KEYBOX and how flexible it is.  Although he attests to not knowing just how secure KEYBOX’s algorithms are (a certain level of paranoia is very healthy!), he and all of KEYBOX’s users can rest assured that under the hood the best of the best of encryption algorithms is at work.

I’d like to take this chance to remind everybody that KEYBOX’s greatest strength is its lack of vendor lock-in.  You can put as many secrets in KEYBOX as you’d like and if you decide to move to another security product you can always export your secrets as a text file.  This text file is completely readable to humans like you and me and you don’t even need another application to view it.

THEY’RE YOUR SECRETS and you have every right to manage them any way you decide to.

 

Thanks again Clinton and the AppAdvice team for spreading the word about KEYBOX!

Post to Twitter

Software Patents – The Growing Epidemic

Preamble

I write this article out of concern for the future of my craft and it’s practitioners. Like many, I’ve been developing software since childhood (My 8th birthday present was a TRS-80).  As ludicrous as it sounds, we software developers live in a world where extortion is not only allowed but is actively encouraged and codified into law by many governments.  I’m of course speaking of patent systems.

 

Where I Stand

I’m not against patents per se. However, being a software developer qualifies me to understand where they succeed, where they fail and WHY.  This article captures my thoughts on the topic and I’d love to hear the opinions of others. (mail me: jay@jayfuerstenberg.com)

 

Where Patents Work

The patent system, in a nutshell, aims to reward inventors and innovators with limited-time exclusive rights to implement a product. The logic being that, without this incentive, companies and entrepreneurs might never invest resources to drive innovation forward. Nations then might become less competitive and end up buying more of their products from abroad. This would lead to job losses and whatnot so patents are the silver bullet to prevent this from happening.  Great!

My favorite example of where patents go right is the story of a Japanese company, HARD LOCK Industry Co., Ltd. Through trial and error this company spent years researching how to make a screw that never loosens. Yes, you heard me correctly, a screw that NEVER loosens! HARD LOCK holds 50 registered patents regarding the various technologies involved in keeping a screw in place.

Their screws are employed in a variety of areas such as heavy machinery where high vibrations would cause any other screw to eventually nudge loose and fall out. If you’re lifting a steel beam with a crane when a screw loosens and something goes wrong millions of dollars of damage and even the loss of human life may result.

If you can grasp how beneficial HARD LOCK’s contribution to humanity is proceed to clap your hands now. The patent system did, and awarded HARD LOCK the limited-time exclusive rights to the technology. HARD LOCK’s competitors cannot simply walk in, reverse-engineer their hard work and sell the same thing at a reduced price (reduced because less R&D goes into reverse-engineering). And this is as it should be.

 

Where Patents Fail

Wait, wasn’t this article supposed to address the evil of software patents? Yes, and to get to that we need to first consider why the software world is nothing like the real world you and I inhabit.

What most people fail to understand (or perhaps don’t care to) is this: Unlike the real world that we are still learning to master, the software world was made by… WE HUMANS.

We designed and created the CPUs, the RAM memory, the hard drives and all the other hardware components that go into a computer, and for one purpose…. so we could have a framework within which to host the software world.

Software is another creation of us cool humans. If you’ve ever watched The Matrix what I’m about to explain will be old hat to you. The reason it’s called SOFTware is that it can be changed at will. In fact, software is infinitely malleable and can model any concept that its developer conceives. The reason software should therefore never be patentable is because there is little to no challenge in creating it. Let me demonstrate this for you…

Here is my software screw (in the Java programming language) that never loosens.

public class Screw {

	/** Screw tightness from 0.0 (fallen out) to 1.0 (tight and snug) */
	private float tightness;

	public void ensureTightness() {
		if (isLoose()) {
			// I'm loose so tighten me!
			tighten();
		}
	}

	private boolean isLoose() {
		return tightness < 1.0f;
	}

	private void tighten() {
		tightness += 0.1f;
		if (tightness > 1.0f) {
			// Whoa, too tight!
			tightness = 1.0f;
		}
	}
}

It didn’t take me years of blood, sweat and tears to make this as it did for HARD LOCK. It took less than 2 minutes for me to write and review its correctness. While I’ve developed in Java for 14 years, even a developer with as few as 2 months Java experience could accomplish the same implementation in the same time frame.

 

 

The point I’m making here is simple, this isn’t the real world. There are no physics to conquer, no biology or chemistry to balance, no gravity to obey.

I and my fellow software developers are masters over the software worlds we create and we make the rules by which they abide. As a consequence, there is very little, if any, R&D needed to create software.

This is patently evident in the software development democratization explosion we have been and are continuing to witness in the smartphone industry. Even before smartphones and the Internet, the software world NEVER needed patents as incentives to innovate. The barrier to entry was already low enough. And now with the Internet, it is only getting lower as computers become ever more affordable and the skills/knowledge more transferable. Time and time again, the only thing software patents have proven themselves to accomplish is the stifling of innovation.

 

Enter the Patent Trolls

Until recently we software developers did not give much thought into defending ourselves from patent trolls. Only recently have patent trolls stepped up their offensive tactics.

What is a patent troll? The term is seen everywhere these days and I imagine most readers who made it this far know the answer. But for those who’d like an introduction, patent trolls are entities who lurk in the dark, waiting for somebody like myself to independently implement something. That something somehow bears resemblance to a diagram or a process they wrote on a paper and submitted to their government. When I stumble into a troll’s hiding grounds, it’ll pounce on me, claiming to own the exclusive rights to implement the idea it says I infringed upon. So am I in the wrong?

What makes patent trolls different from companies like HARD LOCK, is that patent trolls don’t bother implementing the ideas they think they own.

Imagine if HARD LOCK never made screws at all, but still patented the ever tight screw. If another screw manufacturer decided to contribute ever tight screws to society HARD LOCK could not only stop them from selling them but litigate the competitor right out of business. And believe it or not, currently this is entirely legal in many nations. The reason we don’t see patent trolls asserting themselves as much in the real world as we do in the software one is because, again, overcoming physics is a hard thing to do and HARD LOCK’s competitors might never figure it out. If it were easy the HARD LOCK screw would’ve been invented ages ago.

It warrants repeating at this point that software is infinitely malleable. Software developers all have great ideas for products and while they may be innovative, none of them is truly unique. Usually we are just recombining design patterns to solve well known problems that have existed for decades and where the solutions are openly documented for all to see and use.

Development is a creative endeavor and we don’t reference the patent office’s full collection whenever we carry out our craft. So it stands to reason that we are unknowingly infringing upon software patents on a daily basis.

If you were watching the earth from orbit and could visualize each instance of a software patent being infringed upon as an exploding building you would not like what you see. Most if not all the ideas that can be modeled in software have people claiming to be their owners. Do you believe an idea can become property?

 

I Don’t Develop Software. Why Should I Care?

Not everybody makes software but almost everybody uses it. Sometimes it’s the big software maker that gets punished, sometimes it’s the little guy. But in every case the consumer loses. The results for consumers are less selection, and less innovation. The more competition there is, the harder each party fights for your hard-earned money. So if you like low low prices (and who doesn’t?) on top of a healthier economy with more jobs you really should care.

 

Solutions

Many software developers bemoan the state of their respective nations’ patent systems (with America’s USPTO getting its fair share of the love). Some solutions range from abolishing software patents altogether to limiting the amount of money patent trolls can be awarded so as to remove the incentives for trolling in the first place.

While I’m in favor of total abolishment of software patents, I want to introduce a real-world example of a fairly balanced approach.

The Japanese patent system, with it’s stipulation that all inventions (software or not) must somehow overcome an obstacle posed by nature/science, is an interesting approach to patenting from which others could learn. It respects the difference I highlighted earlier between the challenges posed by the real world and the lack of such challenges within the software world. I won’t pretend to be a lawyer and I’m still learning about Japan’s approach but it warrants a read by those interested in patent law.

Another solution, albeit not favorable, might be time itself. China right now is amassing a huge patent portfolio and in time it may be impossible for other nations to make anything without paying licensing fees to Chinese companies. This might force nations like the USA to declare patents as the stiflers to innovation we already know them to be. I’m not advocating doing nothing and just waiting until this happens but it’s one scenario that is currently unfolding and should be on everybody’s radars.

I feel like we are on the cusp of something major here. The internet, for better or for worse, is changing the way we live and work and there are a lot of vestiges of pre-internet life we know we need to cast aside. But a thing like the patent system that was built on the efforts of thousands and which has stood the test of time is not going to roll over willingly. It’s up to people like us to raise voices and take action.

Things we can do right now to protect ourselves from patent trolls and to create change:

Consider what could happen if patent trolls win? Once all the ideas in the software world are taken they could move to other industries:

  • What would the housing industry look like if “shapes engraved on blueprints” could be patentable? Would we all be living in tents?
  • What would the music industry do if “a song rhyming the words ‘girl’ and ‘world’ accompanied by a mellow track” were patentable? No more love songs?
  • What would the fashion industry do if its current environment of open copying went away. Would we all be wearing zippered uniforms if “a combination of convex and concave metal joiners called buttons” were patentable?
I know which future I want to live in.  Do you?

 

Post to Twitter

Plain Text Offenders

In noticing this article today via Hacker News I started to wonder if I should start a “Security Hall of Shame” listing companies that don’t take our security/privacy seriously so people could avoid doing business with them.  Then I discovered that such a site already exists in Plain Text Offenders.  As always I’m the last to know about such great sites.  In case I’m wrong and you haven’t been there you owe it to yourself to check it out and stay safe.

Post to Twitter

KEYBOX on Your Favorite Device

As a result of prMac’s promotion of KEYBOX, the August 6-7 weekend was the best sales weekend to date since it was released a few weeks ago.

Thanks to all of you who purchased KEYBOX! And a special thank you to those who took a moment to rate KEYBOX in the AppStore for your fellow users!

This weekend showed an equal increase in e-mails from customers and prospective customers. The road to releasing KEYBOX to the public has been a long one and it’s great to be able to talk with you and hear all your feedback. One of the recurring themes from these e-mails has been when KEYBOX will be on the iPad/Mac/Android/Windows Phone? Although I like to keep things under wrap (so as not to disappoint anybody) I think it’s time to discuss KEYBOX’s future on different platforms.

Let’s start with the easy ones:

Windows Phone

Unless the market share for this platform grows I won’t be able to recoup my investment. As of today, it’s rapidly losing market share, not gaining it.

Android phones and tablets

Never say never but yeah, probably never. Among its many problems Android is too fragmented a platform (different display resolutions, memory and CPU specs, etc…). The original KEYBOX appeared on Vodafone Japan’s (now SoftBank’s) J2ME platform and was a victim of fragmentation issues. I am not keen on going back to that.

iPad

The iPad could be perhaps in some respects an even better device for using KEYBOX than the iPhone. I’m seriously considering supporting it. Currently KEYBOX works on an iPad in iPhone compatibility mode and if/when an optimized for iPad version is made it’ll be a universal app so that current iPad KEYBOX users won’t need to pay twice. If/When iPad is supported I intend to raise the price to reflect the benefits afforded by the platform.

Mac OS X

KEYBOX on the Mac would perfect the trifecta (phone, tablet, desktop/laptop) in that it could make backups/syncing all the easier. This would obviously be a separate download from the iOS version and the price would be inline with the features/benefit afforded by the Mac platform.

For now…

For the time being taking KEYBOX on iPhone further is the highest priority. Release 1 was about locking down the security and giving it in a simple and clean UI. There are so many great features that didn’t make the first cut and it was difficult to to draw the line but I had to ship KEYBOX at some point. There is a lot in store and I’m thrilled so many of you have joined along for the ride! I value your contributions, and continued feedback and your praise has been a source of inspiration for me!

So thank you! ありがとうございました! Merci! Gracias!

Post to Twitter

Why Digital Privacy and Security are Important for Development

The Guardian is running an article about why digital privacy and security are important for developing nations.

Even developed nations are affected as illustrated by The Tokyo Two who formerly exposed what many already knew about the Japanese Whaling Programme.

 

The take-away from this story: If you use technology, back it up with encryption.  Enough said.

Post to Twitter

The Other Gender – Designing Software for the 21st Century

Half way into KEYBOX‘s development I read this article about somebody who was irritated at always having to declare him/herself as a man or woman. Why would that be an issue?

This person could not identify with being a man, or with being a woman.

I won’t pretend to be able to relate to this. But what I can relate to is being different and being constantly treated as an outsider because of that difference. As a foreigner in japan most websites don’t accept my full name since it’s so long. Japanese names are usually 4-6 kanji characters in length (like 山田太郎).

Japanese website designers rarely if ever consider foreigners whose names aren’t comprised of kanji and it irriates me to no end. Back when I lived in Canada I always developed apps that allowed 50 characters for the first name (well over the likely length) and another 50 for the last name.

So although I cannot relate to being anything other than being a man I can sympathize with being punished for not fitting in.

The Other Gender

Adding “Other” to the list of genders in KEYBOX is a trivial task for me to say the least and it makes me part of the solution, not a perpetuator of the problem. On top of that, users don’t even have to fill in the gender for contacts they add if they prefer not to.

 

I invite more software and website developers to follow suit and enter the 21st century.

 

And maybe one day Japanese websites will hear the plight of us oddball foreigners. Hopefully they can begin to realize that Japan, while still 99% populated by Japanese, has a few of us foreigners who have cash in our wallets and are willing to fork it over if we can fill in our names.

Post to Twitter

The Code Book

The Code Book coverWhile not a new book, The Code Book by Simon Singh is perhaps the most articulate book on the topic of cryptography and cryptanalysis I have ever read. It is a must read for anybody who wants to know how we arrived at our current level of secret keeping and where we might be headed in the next decade. What makes this book stand out in particular is the in-depth historical context provided by Simon Singh without which this book might’ve been a dry listing of various advents of new technology.

There is not much that can be said beyond this without spoiling it so I invite anybody interested in understanding the business of secret keeping, and to what lengths people have tried to advance this science, to read this book.

It is available here from Amazon

Post to Twitter

Upgrading from KEYBOX lite to KEYBOX

Thank you to all the users who’ve contacted me with praise and feedback since KEYBOX was released. In response to your feedback I’m currently drafting up an FAQ page that will help you and your fellow users with common activities. One activity however cannot wait for this FAQ page’s completion: Upgrading from KEYBOX lite to KEYBOX.

 

I want to take this opportunity to discuss how to do this. KEYBOX and KEYBOX lite are distinct and separtate applications. People typically install the free lite edition and test it for 30 days. In that time a lot of secrets get added. After the lite edition expires the user has the choice of either simply exporting his/her secrets and uninstalling KEYBOX lite, or purchasing the full edition of KEYBOX and transferring the secrets to it from the lite edition.

 

How to transfer your secrets from KEYBOX lite to KEYBOX:

  1. Login to KEYBOX lite.
  2. Tap the Import / Export cloud icon in the Top screen.
  3. Tap the Export button in the Import / Export screen.
  4. All the secrets will be backed up now after which KEYBOX lite will provide a web address.
  5. Open a computer browser and type the web address into the browser’s address bar.
  6. The export page will be displayed. Press on the file to start the download.
  7. Check that the secrets file was downloaded.
  8. Download KEYBOX if you haven’t already.
  9. Login to KEYBOX.
  10. Tap the Import / Export cloud icon in the Top screen.
  11. Tap the Import button in the Import / Export screen.
  12. The Import screen will provide a web site address.
  13. Open a computer browser and type the web address into the browser’s address bar.
  14. The import page will be displayed. Specify the KEYBOX secrets file to upload.
  15. Press the Upload button on the Import page.
  16. Check that KEYBOX has properly accepted the file (no errors resulted).

 

KEYBOX backup file

At this point KEYBOX has imported all of KEYBOX lite’s secrets and you are free to keep using them.

If there are any questions regarding this or other parts of KEYBOX please feel free to contact me at support@jayfuerstenberg.com.

Post to Twitter

BCrypt in Objective C

To support BCrypt encrypted login passwords in KEYBOX I ported the very excellent Java implementation by Damien Miller to Objective C.  iOS 4.0 unfortunately does not offer this algorithm out of the box the same way it does SHA-256 and AES-256 and many iOS developers are rolling their own or giving up and settling on SHA-256.

 

Why use BCrypt instead of SHA-256 to one-way hash passwords?

Recently there have been advances in using high performance graphics cards equipped with GPUs to speed up the brute force process of discovering passwords encrypted with SHA-256.  BCrypt is resilient against this strategy by virtue of the fact that it employs a very slow work factor in its hashing.  This is why KEYBOX takes a little while to log you in.  It’s one-way hashing the login password using BCrypt at a work factor of 10.

 

How to use BCrypt in your iOS app.

My ported implementation is called JFBCrypt and relies on 2 other resources, JFGC and JFRandom, which come bundled with it.  As such, it is fairly self contained and does not require any external dependencies.  Just drop these files anywhere in your iOS project and include logic similar to that shown below.

Example usage:

NSString *salt = [JFBCrypt generateSaltWithNumberOfRounds: 10];
NSString *hashedPassword = [JFBCrypt hashPassword: password withSalt: salt];

JFBCrypt is covered under the very liberal Apache license and can be included in both open source and closed source apps.  Damien Miller’s original license is also included in accordance with his wishes.

 

If you have any questions or feedback feel free to contact me at jay@jayfuerstenberg.com.

Post to Twitter

Introducing KEYBOX for iPhone and iPod touch!

Before starting, I want to thank my wife and son for their frequent weekend sacrifices over the past year. They literally made KEYBOX possible. I’d also want to thank the reviewers at Apple if for no other reason than their job is a thankless one.

 

What is KEYBOX?

Privacy is a topic near and dear to me. I wrote the original version of KEYBOX to scratch a personal itch back in 2005.

My apartment was broken into and many of my and my wife’s belonging were stolen, even using our bags to haul it all away. Worse of all the thief left us a note showing off how proud he was. This was not our home anymore and everything we thought was private was no longer. Only after becoming victims did we start to invest in dimple keys and other preventative measures.

For myself, it didn’t stop there. I was compelled to take my privacy very seriously from that moment onward. The original version of KEYBOX was the culmination of careful design and development to address this.

2009 and 2010 were years that presented challenges to protecting people’s privacy. I wrote KEYBOX for the iPhone in response to this changing lanscape.

I don’t believe privacy is a dying concept as Mark Zuckerberg would have us believe. Privacy has never been more important. As we move more of our lives onto the cloud we open ourselves to more security risks. Who we are and what we do is no longer tucked away safely in a drawer in our homes. It’s now sitting on a 24h accessible server on the Internet and we are no longer in full control of our privacy.

How KEYBOX works and what distinguishes it from alternatives is a bit too much for this post. I’ll be discussing the design, development, marketing decisions behind KEYBOX and where the app is going in the future in future posts.

If you are serious about security and your own privacy you can learn more here… http://www.jayfuerstenberg.com/keybox/

Post to Twitter

When Patents Attack!

A new episode of This American Life deals with the increasingly hot topic of software patents and patent trolls.

Patent trolls are companies that, by themselves, contribute nothing to society and instead acquire patents with the sole purpose of extorting money from entities that DO create value and contribute to society.  They claim to own ideas, most of them obvious, and that implementors of these ideas are required to pay for them.

Patent trolls are a grave threat to software developers large and small, and the users who stand to benefit from this software.  It is therefore crucial that all software developers prepare themselves.  A first step includes understanding their tactics by tuning in to this episode.

Post to Twitter

Yes, I’m a Chicken Shit

Tim Bray recently posted his opinions on the lack of quality regarding the media’s reporting of Japan’s recent nuclear disaster.

I agree with most of what he has to stay.  All except the part about people leaving the Tokyo region.  He believes it to constitute “chickenshit stupidity”.

Anybody who has lived in or around Tokyo knows that, should any of the nuclear reactors at the Fukushima Daiichi plant release enough radioactive material to be considered harmful, it’ll already be too late to leave.  The Kanto region has a population of over 34 million people, about the same as all the municipalities of my native Canada combined.  Competing for a plane or train ticket and succeeding is nearly impossible.  Walking would be faster, though you might not get far.

In my case, I learned on March 15th that most of my expat coworkers were in the process of or had already left Tokyo, some going as far as their home nations.  Some of these coworkers experienced Chernobyl from many times further away than Tokyo is to Fukushima.  Now Fukushima is no Chernobyl.  I know that.  But honestly, I don’t know much else about the Fukushima nuclear reactors.  At the time I arranged plane tickets bound for Osaka even the “experts” didn’t know much more than anyone else about what was going on.  All that was known was that the situation was worsening, not improving.

Coincidentally the radiation levels in Tokyo on March 15th were approx. 4.5x higher than average.  Nothing life threatening but it proved that Fukushima Daiiachi was leaking/venting and that the winds could carry that material all the way down to Tokyo.  My thinking was simple… Should I wait until the really potent stuff come this way before deciding to protect my family?

The second reason for leaving Kanto and going to Osaka was to get a break from the bloody aftershocks for a while.  It seemed that every hour saw a sizable tremor and that began to take a toll on our nerves.  Myself and everybody I know was experiencing dizziness many times a day and imagining aftershocks that weren’t really happening.  It felt as if the part of my brain that stays a bit awake to sense motion during sleep had been on special alert for a full week after the megaquake and with each night quake (usually a M4-6) it was impossible to get quality sleep.  It should be noted that I’ve lived in Kanto for nearly 10 years and I’m used to earthquakes.  Usually I don’t even drop what I’m doing when the earth starts moving.

In any case Osaka was a great respite for us.  The earth never moved once.  The stores there were fully packed, and there were no rolling blackouts to speak of.

And funny enough, as soon as I dropped my luggage after arriving home this afternoon a M6.1 earthquake in Miyagi began to rattle things in the kitchen.  I don’t know how I’ll respond to the prospect of more quakes but the last week in Osaka was one this chicken shit will never regret.

Post to Twitter

Leaving the Kanto Region Temporarily

Due to the nuclear situation up in Fukushima prefecture I will be taking my family west (upwind) to Osaka for at least a week.

Thank you to those who’ve sent warm wishes this way.

If you can find it in your hearts, please donate money to the people in Miyagi and Fukushima (not to mention Asahi in Chiba). They need it more than ever now.

Thank you! Jay Fuerstenberg

Post to Twitter

Hot Potato – Thoughts on Java Exceptions and Error Handling

Lately I’ve been giving thought to what error handling means, what it should mean and where, if any, the gaps are.  Like everyone else I hate errors.

Whenever possible I strive to honor user intentions and have come to think of displaying error messages as something to be avoided or at least discouraged.  Often what we call error handling amounts to mere error reporting.  In other words, the literal meaning of error handling, “handling” of errors does not occur.

The reasons for this are numerous no doubt and while I don’t want to target a single culprit I need to begin with the one that has gone overlooked for far too long: Java exceptions.

The Java exception

Java exceptions are designed not to handle errors but to report them.  At the core of the Java exception is a message, a single snippet of text intended for human consumption.  The contents of this message can be anything but it makes sense to restrict oneself to describing the error’s cause.

But if exceptions are intended for people how is an application expected to handle them?  The short answer is it can’t.  At least not easily, and certainly not without violating Information Hiding, one of the most basic tenets of OOP.  In both directions in fact. The caller method needs to know the inner workings of the callee method to solve the issue (hint: it shouldn’t know the inner workings), and the callee has to know that the caller is going to correct it (it can’t even know who the callers will be at design time).

A side effect of this half-baked design decision is what I like to refer to as the “Hot Potato” game.  By “hot potato” I mean hard to handle, easy to throw.  Java’s approach to error handling is of course by throwing exceptions, often to the caller of the offending method in the hopes that it will be caught and somehow corrected.  It involves a lot of effort and finger-crossing to work.

The outcome is obvious.  The application just catches exceptions and envelops them in other exceptions and throws them further up the call stack.  Eventually a catch all error handler will report an error message on screen for the end-user to interpret and correct.  Whether the error can be corrected or not is subject to the developer written error message.

In all fairness, the intent behind Java exceptions was to produce cleaner looking code (in comparison to applications written in C/C++) and in this regard it largely succeeded.  But this came at the cost of expecting end-users to solve problems.

Before I move on I would like to acknowledge one good solider in all this.  The only good Java exception is IllegalArgumentException as it communicates the caller’s offense to itself without violating Information Hiding.  Still, communicating this fact needn’t necessarily occur by throwing an exception.  There are alternatives!

Alternatives

Others have documented these problems before and I’d like to take the time to propose (or for some ‘reintroduce’) alternatives.  First I want to assert that solving a problem as soon as it becomes apparent is better than passing it/throwing it.  Solving a problem means understanding and keeping in mind the end user’s intentions and exhausting all means to carry them out after the initial attempt fails.  The truth is that it’s not always possible but trying is important.

Using error codes

The C language solved the problem of communicating failures with the advent of error codes.  Error codes have two traits that makes them perfect for error handling.
  1. They are not throwable.  We have to handle that hot potato!
  2. They are comparable by the application.

The application can distinguish between numeric codes to take appropriate action on its own and without user intervention.  The SQLite C library has a good example in the sqlite3_step function.  It returns an integer to indicate success (SQLITE_DONE) or any of the supported error codes. Objective C goes one step further than C in offering the elegant NSError class.  In this approach a method can accept a pointer to a pointer to an NSError object should it be expected to disclose its success/failure.  Not passing this pointer to a pointer indicates a lack of interest in the method’s success/failure.  Should an error occur, NSError’s code ivar will be a value other than zero which is easy to test after a method has returned.

- (User *) userWithName: (NSString *) name error: (NSError **) error {
	if (name == nil) {
		*error = [NSError errorWithDomain: @"some domain" code: 1 userInfo: nil]; // 1 = no name!
		return;
	}

	...
}

The advantage of the NSError approach is being able to embed other information in the class in addition to the error code via the userInfo dictionary.

 

Both C style error codes and Objective C’s NSError are more responsible forms of error handling because they cannot be thrown yet still convey the cause of an error.  The optional nature of NSError makes it especially attractive in scenarios where we know an error will not happen or is insignificant (ex: attempting to delete a record which no longer exists).  These approaches, while more prevalent on some platforms, can also be applied to Java applications with the same effect.

Do they violate Information Hiding?  Not in a strict sense.  Although we are encouraging responsible error handling, error codes unlike exceptions do not disrupt the application’s execution flow with the expectation on the caller to handle anything.  Nothing is being thrown.  A code is being returned.  The caller can choose to retain it or ignore it in which case it will be discarded.  The code is designed to state success or any number of reasons for failure.

Conclusion

Java exceptions don’t solve problems.  They report them via exceptions and a high-standard of description is not enforced.  It is an approach that concerns itself with solving one problem (code cleanliness) but introduces other problems in its wake that result in a worse user experience overall.  The Java approach has been carried over to other languages like PHP, C# and others and has gained much acceptance but perhaps it’s time to rethink its merits and investigate those of other approaches.

 

Post to Twitter

Error Messages – Another installment of bad software design

Last weekend I purchased the Sharp DB-HDS65 Blu-ray/HDD TV recorder.
I’ve been a Sharp fan since the day I stepped foot in Japan so it pains me to have to report that last night the below error message appeared on my TV.

Sharp BD-HDS65 failure

 

For those who don’t read Japanese it says “Error occurred during software update.  Please contact our support staff.”

I didn’t ask it to update its software but whatever.  I realize that, internally, this is essentially a computer masquerading as a video appliance and it already does a lot automatically for me.  Like any error message I’m prompted with, I expect there to be an “OK” button or similar to acknowledge the failure and move on.

 

Except this time there was none.  The remote control, aside from the POWER and volume buttons, is now unresponsive.

Wanting to find a quick fix, I researched online and found some people experiencing the same issue.  Their tales included downloading software from Sharp’s website and pressing the RESET button repeatedly in vain.  With nothing to lose I downloaded the recommended software update from Sharp’s website and placed it on a USB thumb drive as per their instructions.

Next I proceeded to insert the USB thumb drive into my Blu-ray recorder.  Nothing.

Turned off/on the machine with the USB thumb drive inserted.  Nothing.

Pressed the RESET pin with the USB thumb drive inserted. Nothing.

Unplugging the device for the night and plugging it back in the next morning. Again nothing.

I thumbed through the user manual in search of further clues.  Of the 100 odd error messages listed (another cause for concern if there needs to be this many) this one was missing so I was left in the dark.  After one phone call it seems Sharp will be dispatching a maintenance person in a few days but in the meantime my family and I cannot watch recorded programs.

How could this problem be prevented?

The purpose of the post is of course not to bash Sharp but to exhibit a bad software design and how it could’ve been designed better.  First we need to acknowledge that software updates are optional and should NEVER impede the use of the device.

This is easily Sharp’s biggest violation.

If the device’s software is damaged to the point where it really is no longer usable an error message like “I’m broken and can no longer work” should be displayed instead.  In my case, seeing as how the device is still periodically waking up to record pre-programmed shows, I don’t believe it to be broken in any way.  Solving this problem is accomplished by adding an “OK” button to this error message.

 

Sharp’s second violation is making an appliance behave like a computer, even if it is one internally.  Not everybody understands computers.  Not everybody has an internet connection to be able to download the updates, or even the instructions themselves.  Appliances should hide the computer within.

Real Life

For a real-life example of a software update function done right, we need only look to Nintendo’s Wii.  The Wii’s software updates are completely optional.  If I don’t have an internet connection the Wii will be oblivious to updates and if I do have one the Wii will use Wi-Fi to obtain the updates without me needing to know where to download it.  I just need to watch the updating progress bar over a cup of coffee.  Simple.

 

Considering the total cost to Sharp (in documentation, support, maintenance, and now their reputation) one would think it would also be in their interest to make problems easily solvable by end users.  I hope the next generation of this device (or the software update I’m supposed to benefit from) will rectify this and restore my faith in Sharp.

Post to Twitter

HgInit – A great Mercurial resource

Using a MacBook for most of my Objective C development, I found it useful a couple of years ago to switch from Subversion to Mercurial for my version control needs.

In looking for some in-depth Mercurial information I stumbled upon a great resource by Joel Spolsky of Joel On Software fame.

http://hginit.com/index.html

Joel explains how to shake off the Subversion mindset and why Subversion should be dropped in the first place.  Whether you’re working alone, or in a team and having difficulty with the bottlenecks imposed by Subversion, you’ll find this website to be a great way to get up to speed with Mercurial.

Post to Twitter

Preserving memory on the iPhone: The case for lazy-initialization and aggressive releasing

In a previous post I discussed garbage collection and how to abstract away the logic to make it easier to manage memory. I now want to take the opportunity to talk about a complimenting, higher level strategy for managing memory: Lazy-initialization and aggressive releasing.

Memory is at a premium on the iPhone and, in the case of data/information applications, the user is only interacting with a small part of the application at any given time. It therefore makes sense to only allocate enough memory for the part being used. Planning what parts will undergo use up front is difficult at best but the simpler method of lazy-initialization exists.

Lazy-initialization is the act of foregoing initialization of a member until it’s absolutely needed. For instance, when a login view will appear it may need to initialize a set of components.

- (void) viewWillAppear: (BOOL) animated {

	[super viewWillAppear: animated];

	[self lazyInitUsernameTextField];
	[self lazyInitPasswordTextField];
	[self lazyInitLoginButton];
}

An example lazy-initializer method might look like this…

- (void) lazyInitUsernameTextField {

	if (_usernameTextField != nil) {
		// The text field is already initialized so return.
		return;
	}

	// The text field has yet to be initialized so do so now...
	_usernameTextField = [[UITextField alloc] initWithFrame: CGRectMake(20.0f, 50.0f, 200.0f, 30.0f)];
	// Logic to customize the text field goes here.

	[self.view addSubview: _usernameTextField];
}

The beauty of lazy-initialization is it allows the caller to not care whether the member is initialized or not at the time of method invocation. However, by the time the method has completed executing the member is known to be initialized.

 

In other words a one-liner call is all it takes to ensure the state of the application beyond the point of invocation. It is equally appropriate to invoke a lazy-initializer method from within another, and to even set up a chain of such lazy-initializations as needed.

On the other end of memory management is aggressive releasing. I’ve found it handy to use a protocol, JFLazyInitializedMemberReleaser, to expose a method tasked with releasing only members which were lazy-initialized.  Below is an example releasing method…

- (void) releaseLazyInitializedMembers {

	[_usernameTextField removeFromSuperview];
	[_passwordTextField removeFromSuperview];
	[_loginButton removeFromSuperview];

	JFRelease(_usernameTextField);
	JFRelease(_passwordTextField);
	JFRelease(_loginButton);

	if ([super conformsToProtocol: @protocol(JFLazyInitializedMemberReleaser)]) {
		[super releaseLazyInitializedMembers];
	}
}

This method should be invoked from some or all of the following methods (on a case by case basis)…

 

dealloc viewDidDisappear viewDidUnload didReceiveMemoryWarning

Putting it all together

When a view appears for the first time it lazy-initializes only the members it needs. Interaction with the view may trigger further lazy-initialization over time (action sheets that slide into view etc…) When the user transitions to a different view the aggressive releasing method jettisons the members which are no longer of use. Which members are released is arbitrary and depends on the application’s needs.

If/when the user returns to the view the viewWillAppear method will be invoked once again and re-lazy-initialize the members. The user is none the wiser as the view does not appear to have changed from the last time it was used. Finally, all this was accomplished while still keeping the memory consumption to a minimum.

Post to Twitter

Failing Early – A short story of bad software design

A few years back I needed to withdraw money from my bank account. I proceeded to the closest ATM and the typical withdrawl process ensued… I inserted my bank card, pressed the “Withdraw” button, entered my PIN code, then the amount to withdraw, and lastly the “Confirm” button. The ATM generated some mechanical noises and after 10 seconds the ATM spit my card back out and printed a message on a receipt to the effect that the banks involved cannot process transactions in conjunction at this hour (it was about 6:30pm).

It should be mentioned at this point that both my bank and the bank whose ATM I was using are Japanese. I won’t side track into the joke that is the Japanese banking industry but I will say that if you’ve never had to deal with Japanese banks then consider yourself lucky. Well, having gone through so many motions for this ATM my head nearly blew up.

Continue reading

Post to Twitter

Garbage collection on the iPhone

While Objective C 2.0 provides automatic garbage collection (GC) this facility is not available on the iPhone. However, mobile devices like the iPhone with limited memory are where proper memory management practices must be well followed.

In the course of my development I found it convenient to abstract away most of the calls to retain and release with a set of C macros I created and now share here. If memory management logic is polluting your code base or debugging memory leaks is giving you a headache feel free to use these macros to simplify your life.

Download: JFGC.h

//	JFGC.h
//
//	Created by Jason Fuerstenberg on 2008/05/01.
//	Copyright 2008 Jason Fuerstenberg
//	http://www.jayfuerstenberg.com
//
//	Licensed under the Apache License, Version 2.0 (the "License");
//	you may not use this file except in compliance with the License.
//	You may obtain a copy of the License at
//
//	http://www.apache.org/licenses/LICENSE-2.0
//
//	Unless required by applicable law or agreed to in writing, software
//	distributed under the License is distributed on an "AS IS" BASIS,
//	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//	See the License for the specific language governing permissions and
//	limitations under the License.

/*
 * The JFAssign macro assigns the value of one object reference to another.
 */
#define JFAssign(to, from) { {id __temp__ = from; JFRelease(to); [__temp__ retain]; to = __temp__; } }

/*
 * The JFRelease macro releases an objective C object using the release method.
 * If the object reference is nil nothing will be released.
 * The object reference is then assigned to nil.
 */
#define JFRelease(a) { {id __temp__ = a; if (__temp__ != nil) { [__temp__ release]; a = nil; } } }

/*
 * The JFFree macro releases a non-objective C memory buffer using the free function.
 * If the pointer is nil nothing will be freed.
 * The pointer is then assigned to nil.
 */
#define JFFree(a) { if (a != nil) { free(a); a = nil; } }

How To Use

 

Instead of writing this…

- (void) setName: (NSString *) name {
	if (_name != nil) {
		[_name release];
	}
	_name = name;
	[_name retain];
}

You now write this…

- (void) setName: (NSString *) name {
	JFAssign(_name, name);
}

And now dealloc methods look like this…

- (void) dealloc {
	JFRelease(_nameLabel);
	JFRelease(_nameTextField);
	JFRelease(_passwordLabel);
	JFRelease(_passwordTextField);
	JFRelease(_loginButton);
	JFFree(_responseBytes);

	[super dealloc];
}

Instead of like this…

- (void) dealloc {
	if (_nameLabel != nil) {
		[_nameLabel release];
		_nameLabel = nil;
	}
	if (_nameTextField != nil) {
		[_nameTextField release];
		_nameTextField = nil;
	}
	if (_passwordLabel != nil) {
		[_passwordLabel release];
		_passwordLabel = nil;
	}
	if (_passwordTextField != nil) {
		[_passwordTextField release];
		_passwordTextField = nil;
	}
	if (_loginButton != nil) {
		[_loginButton release];
		_loginButton = nil;
	}
	if (_responseBytes != nil) {
		free(_responseBytes);
		_responseBytes = nil;
	}

	[super dealloc];
}

Developers coming from languages like Java with automatic GC will find this style more natural as a call to JFAssign(a, b) is similar to a = b and a call to JFRelease(a) to a = null;

 

Post to Twitter

Why do computers/devices exist?

It seems odd that a post could be dedicated to such an obvious topic but given the state of computing today it is actually well warranted.

While there may be more than one answer to this question let me propose what I consider to be the best one… Computers exist to do the things that… 1. people cannot do easily, quickly, safely, accurately. 2. people simply dislike doing. In simpler terms computers are here to remove burden and free us to do the things we “actually like doing”.  If you can often walk away from a computer and let it do its thing, life is good.  However, we all know this is a fantasy and that computers left to themselves are useless.

People and computers were meant to work together.

Much as it is true with teams of people, the quality of work produced by this person/computer duo is largely dependent on how well the two interact with one another. Making users understand computers has, to a large degree, been tried. The other approach is having computers/software reciprocate by understanding users and their intentions.

Post to Twitter

An introduction

Firstly, welcome to my blog.

I’m not sure what structure this blog will take, if any, but in the coming weeks and months I’ll be sharing thoughts and experiences regarding design and development.  I’ll also occasionally link to sites that I follow in the interest of spreading news.

It is my hope that what is shared here will benefit and inspire others to share in the same spirit.

Post to Twitter