Frank Krueger: Coding in Your Head

I’m terrible at coding interviews – some busy bee dusts off a tricky algorithm that they studied in college and asks you to (1) originate it from a poorly stated problem and (2) live code it in front of them.

This isn’t how I work. Like most programmers who survive more than a few years in this business faced with a novel or difficult problem, I do the majority of my design work in my head – slowly.

Realm of Endless Possibilities

The problem gets repeated endlessly: “The user wants to accomplish X, Y, and Z – I will need to talk to data sources I, J, K – I will use algorithms A, B, C – they are connected in this configuration or that – information will be on a screen that looks like…”

I try out all the permutations of data structures, objects, their relationships to one another, algorithms that I already know, and algorithms that I note to seek out. I think through the user interface – attempting to limit the number of choices the user has to make to do repetitive tasks while still trying to giving them a new power.

Steeped in years of OOP programming, all this design work culminates in an object schema in my head. Known classes and their relationships to other classes are built and toyed with. I refine this graph by running many algorithms across it to see how nasty my layers of abstraction and encapsulation make moving data around (remember, in the end, the most important thing to your program is the data – not how you represent it). I look at it to see how easy it will be to extend or flat out replace in the future.

This is a slow process. It’s why I have a list of 100 “potential next apps”. They’re up in my head (or at least a few top candidates) while I toss them around and poke and prod at their code.

Coding It

Once a design is deemed robust, useful, and interesting enough, it’s time to sit down and code it. At this point you are basically limited by your programming language. This is why I’m a programming language nerd and relentless critic.

I don’t care about powerful programming languages because they save me from typing. I care about them because they allow me to get closer to my mental design than less powerful languages.

Designs of the mind are necessarily abstract – unconcerned with particulars of language. My “head design language” is just objects, interfaces, methods, properties, and events. Call this OOP 1.0. (As I learn functional programming, my language is slowly turning to records, abstract data types, interfaces, and functions.)

When I sit down to write these, any boilerplate that the language forces on me becomes an annoyance. C++ and Objective-C that require designing a memory strategy are profoundly annoying (I can barely get my own designs right, and now the fracking computer needs help too?). C#’s lack of metaprogramming and first class events is another annoyance. F#’s single-pass compiler that makes you order every declaration and even your source files (seriously, what decade is this?) is, you guessed it, annoying. Even trivial syntax gets annoying at this point – why do I have to write all those silly characters? { ; } oh my.

The tools we use also become obstacles. Intelligent IDEs that are intended to make coding easier become enemies with every spinning beach ball – with every hidden setting – with every error message. Imagine trying to create an intricate sand castle on the beach during a hurricane. No wonder text editors such as Sublime are such hits.

So your beautiful mental design gets compromised into some language or another. This is why we call it coding – we are encoding a design into some barbaric text format that only highly paid professionals and intelligent 13 year olds can understand. Anyway…

That’s all to say that it’s best to burn through all the bad designs in your head so that only the decent ones have to suffer this transition to code.

Some More Thoughts

It’s a slow process but it can’t be sped up. No, test driven development is not an answer. TDD causes you to hash out a design – but one that’s biased to one consumer – the tests. It neglects the most important consumer – the end user. Also I am happy to throw out a design that I’ve been mulling over for a week. I have never once seen a TDD advocate throw away a week’s worth of Asserts – no they just get painfully “refactored” into the next design option.

It’s not a perfect process because your initial designs are never right. Certainly it saves you from writing endless numbers of throw away prototypes before you settle on a good design – but it won’t be a perfect design. It will have to be changed once you’ve implemented the app and learned what the app really is and how people really use it.

Frank Krueger: Many Levels of Rejection

Submitting apps to the App Store is filled with many wonderful opportunities to be rejected. Let’s count them!

1. Compiling/Building your app is the first possible level of rejection. It’s usually your fault, but some days…

2. Signing your app is also an adventure in rejection with the added joy of creating multitudes of profiles and app IDs than you really don’t know what to do with but are too afraid to delete.

3. Sometimes the phone itself will reject you next. Maybe Springboard is having a bad day, or maybe you really have made a mess of those profiles…

4. Hey look at me! The watch wants in on this game too! It likes to reject you for a variety of reasons but doesn’t like to tell you which. You’ll have to dig into the logs to find its secret motives.

5. Time to submit that puppy and get rejected by the iTunes Connect! iTunes is actually pretty good at this whole rejection thing and does its best at helping you through the difficult times.

6. Well now that you’re uploaded, surely the app… whoops. Nope. Time for the little Prerelease Binaries to reject you. Oh you didn’t know about that esoteric requirement? You read every guide, right? Right?

7. Time to submit for review and let the humans… nope, wrong again. Another computer can reject you now before a human ever sees it. Watch your inbox cause iTunes Connect has no idea what that computer is doing.

8-1,000. Finally after all that, you can be rejected by a human. This rejection process is long, filled with unspoken truths, false assumptions, and bitter quibbles. But at least it’s a human…

1,001-1,024. It was all worth it, your app is in the store and is running gr… oh, it crashes on iPad 2s when you rotate the screen during the 5th moon of the year. 

So close.

Xamarin: A Scalable Introduction to Vector Drawables

Among the many novelties brought to Android in 5.0 Lollipop, vector drawables are one of my favorite additions. They manage to both solve one of the oldest Android pain points (wide range of screen densities) and also pave the way for much better interactions in our apps. Introduction to Vector Drawables What exactly are vector […]

The post A Scalable Introduction to Vector Drawables appeared first on Xamarin Blog.

Michael Ridland: FreshMvvm Quick Start Guide

FreshMvvm is designed to be easy and simple. So getting started is also fairly simple. Step 1. Start new project Start a new Xamarin.Forms Project using Portable Class Libraries. Step 2. Obtain FreshMvvm from Nuget Obtain FreshMvvm from Nuget by searching for FreshMvvm, make sure to do this on your Xamarin.Forms PCL project. Step 3. […]

The post FreshMvvm Quick Start Guide appeared first on Michael Ridland.

Xamarin: Xamarin.Studio 5.9 Enhancements

Our latest release of Xamarin Studio includes many great new features, including a new wizard to walk you through creating projects, a new publishing workflow to simplify publishing, archiving, and code signing, fancy new debugger visualizers, support for C# 6, and much more! New Project Dialog The File > New experience has been completely redesigned […]

The post Xamarin.Studio 5.9 Enhancements appeared first on Xamarin Blog.

Michael Ridland: FreshMvvm – A Mvvm Framework designed for Xamarin.Forms

Now available via Nuget FreshMvvm is a Mvvm framework that’s designed specifically for Xamarin.Forms. The reason I say it’s designed for Xamarin.Forms is because it plays on Xamarin.Forms strengths and fills in ONLY the missing parts. It has a requirement for Xamarin.Forms and therefore is smart and can do thing such as wiring up the […]

The post FreshMvvm – A Mvvm Framework designed for Xamarin.Forms appeared first on Michael Ridland.

Adam Kemp: Taming The Android Activity, Part 2

In part one of this series I covered how to use a Fragment to maintain state through configuration changes. In part two I will cover how to launch a new Activity (in-process or not) and wait for its results using C#’s async/await feature.

Starting Activities

As mentioned in part one, the Activity is designed to let applications reuse pieces of other applications. For instance, if you need to let the user pick a photo then you can construct an Intent object that describes what you want to do (pick a photo), and the OS will find an Activity for one of the installed applications that can satisfy that request. The other Activity may be in another application, but the Intent allows you to send it information about what you want, and then later it can send back the results (through another Intent).

The way the API works is you call StartActivity (a method in Activity) and give it either an Intent object or a Type (which will be used to construct an Intent). When you do that the OS will find the proper Activity, create it (possibly in another process), and then show it the user. Once that Activity is finished (either by the user pressing the back button or the Activity calling Finish()) then your original Activity will resume.

However, that’s only for a simple case: launching a new Activity and ignoring any results. If you actually wanted to get information back from the other Activity then you need to instead call StartActivityForResult. This method is just like StartActivity, but it also takes an int that can be used to identify the request. Then you have to override the OnActivityResult method, which will give you back the request identifier along with a ResultCode and an Intent (for extra information). That basically looks like this:

private const int ImagePickerRequestCode = 1000;

private void LaunchOtherActivity()
{
var intent = new Intent(Intent.ActionGetContent);
intent.SetType("image/*");
StartActivityForResult(intent, ImagePickerRequestCode);
}

public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if (requestCode == ImagePickerRequestCode && resultCode == Result.Ok)
{
// Get the image from data
}
}

The Problem

There are several problems with this, and the root of all of them is that all results for any Activity you launch must go through OnActivityResult. This means that any time you launch an Activity and want results you have to put some code in that function to handle the results. This is why you need the annoying int requestCode argument: that is the only way to identify which Activity you were launching so that you know what to do with the results. Now you have to be sure that each type of Activity that you launch in this way uses a different number, which is annoying.

Another problem is that this splits up your code. You start the Activity in one place, and then you handle the results elsewhere. There’s no callback or anything that connects the two. You just have to know to go find that other function to see how the results are handled.

The worst problem is that this makes it very difficult to properly decouple responsibilities between views. What if you want to launch another Activity from a view inside a popup? You still have to handle the results in the Activity itself, and then you somehow have to get the results back to the view inside the popup.

This was my motivation for finding a better way. When you write a large application in Android you might have many different kinds of activities that you want to launch and then gather the results from, and forcing all of that code to go through a single function makes it very difficult to maintain.

Imagine a Better Way

Before we start trying to implement anything let’s first think about what we want the API to look like (always a good first step to avoid APIs like this).

Obviously launching a new Activity and getting results is an asynchronous operation so we’re going to have some kind of asynchronous API. We could do that with callbacks, which would be a huge improvement, but C# has an awesome feature that makes this even better: async/await. Using that feature we could imagine an API that looks like this:

var intent = new Android.Content.Intent(Android.Content.Intent.ActionGetContent);
intent.SetType("image/*");
var result = await StartActivityForResultAsync(intent);
if (result.ResultCode == Result.Ok)
{
// Get the image from data
}

This looks awesome. There’s no request code, and all of the code is in one place. Best of all, there’s not even a callback. This code reads like normal synchronous code.

Gathering Requirements

Now that we know what we want the API to look like let’s think about what we need to accomplish it. One of the benefits of the work we did in part one of this series is that each Activity (and also each Fragment) in our application shares a base class. That provides us with an opportunity to put some bookkeeping in the base class that can help us achieve our goal. Based on the API we have to start with, and the API we are trying to build, we need to keep track of this information:

  1. A request code for each launched Activity. To avoid requiring the caller to give us one we also need to somehow come up with new unique request codes automatically.
  2. A TaskCompletionSource that can be used to provide the results asynchronously to the caller (via its Task property).
  3. A mapping between the request codes and the TaskCompletionSources.

Based on this we can start to see an implementation forming. We can use an auto-incrementing request code (starting at some arbitrary value), and we can use a Dictionary to map between the request codes and the TaskCompletionSources.

While we’re at it we will also solve another challenge that we often face when dealing with these Activity results: OnActivityResult is called before OnResume, which in some cases may be too early to actually deal with the results. Since we’re already handling sending the results back asynchronously we can fix this by also delaying the results until after OnResume, which is far more useful.

Implementation

In the spirit of keeping as much logic in the Fragment instead of the Activity we will be putting this API in the FragmentBase class that we created in part one of this series. This is also important because we don’t want to lose the bookkeeping information if there is a configuration change (like if the user rotates the device after you start the new Activity but before you get the results).

Our FragmentActivity class will be the same as before, but we will add some new code to the FragmentBase class. First, we need an interface for the results returned by our async method:

/// <summary>
/// The information returned by an Activity started with StartActivityForResultAsync.
/// </summary>
public interface IAsyncActivityResult
{
/// <summary>
/// The result code returned by the activity.
/// </summary>
Result ResultCode { get; }

/// <summary>
/// The data returned by the activity.
/// </summary>
Intent Data { get; }
}

Now we need to add our new methods to the FragmentBase class. I have omitted the parts that were unchanged for brevity.

/// <summary>
/// The base class for top-level fragments in Android. These are the fragments which maintain the view hierarchy and state for each top-level
/// Activity. These fragments all use RetainInstance = true to allow them to maintain state across configuration changes (i.e.,
/// when the device rotates we reuse the fragments). Activity classes are basically just dumb containers for these fragments.
/// </summary>
public abstract class FragmentBase : Fragment
{
// This is an arbitrary number to use as an initial request code for StartActivityForResultAsync.
// It just needs to be high enough to avoid collisions with direct calls to StartActivityForResult, which typically would be 0, 1, 2...
private const int FirstAsyncActivityRequestCode = 1000;

// This is static so that they are unique across all implementations of FragmentBase.
// This is important for the fragment initializer overloads of StartActivityForResultAsync.
private static int _nextAsyncActivityRequestCode = FirstAsyncActivityRequestCode;
private readonly Dictionary<int, AsyncActivityResult> _pendingAsyncActivities = new Dictionary<int, AsyncActivityResult>();
private readonly List<AsyncActivityResult> _finishedAsyncActivityResults = new List<AsyncActivityResult>();

#region Async Activity API

public Task<IAsyncActivityResult> StartActivityForResultAsync<TActivity>(CancellationToken cancellationToken = default(CancellationToken))
{
return StartActivityForResultAsyncCore(requestCode => Activity.StartActivityForResult(typeof(TActivity), requestCode), cancellationToken);
}

public Task<IAsyncActivityResult> StartActivityForResultAsync(Intent intent, CancellationToken cancellationToken = default(CancellationToken))
{
return StartActivityForResultAsyncCore(requestCode => Activity.StartActivityForResult(intent, requestCode), cancellationToken);
}

public override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
AsyncActivityResult result;
if (_pendingAsyncActivities.TryGetValue(requestCode, out result))
{
result.SetResult(resultCode, data);
_pendingAsyncActivities.Remove(requestCode);
_finishedAsyncActivityResults.Add(result);
}

base.OnActivityResult(requestCode, resultCode, data);
}

public override void OnResume()
{
base.OnResume();

FlushPendingAsyncActivityResults();
}

private Task<IAsyncActivityResult> StartActivityForResultAsyncCore(Action<int> startActivity, CancellationToken cancellationToken)
{
var asyncActivityResult = SetupAsyncActivity();
startActivity(asyncActivityResult.RequestCode);

if (cancellationToken.CanBeCanceled)
{
cancellationToken.Register(() =>
{
Activity.FinishActivity(asyncActivityResult.RequestCode);
});
}

return asyncActivityResult.Task;
}

private void FlushPendingAsyncActivityResults()
{
foreach (var result in _finishedAsyncActivityResults)
{
result.Complete();
}
_finishedAsyncActivityResults.Clear();
}

private AsyncActivityResult SetupAsyncActivity()
{
var requestCode = _nextAsyncActivityRequestCode++;
var result = new AsyncActivityResult(requestCode);
_pendingAsyncActivities.Add(requestCode, result);

return result;
}

private class AsyncActivityResult : IAsyncActivityResult
{
private readonly TaskCompletionSource<IAsyncActivityResult> _taskCompletionSource = new TaskCompletionSource<IAsyncActivityResult>();

public int RequestCode { get; private set; }

public Result ResultCode { get; private set; }

public Intent Data { get; private set; }

public Task<IAsyncActivityResult> Task { get { return _taskCompletionSource.Task; } }

public AsyncActivityResult(int requestCode)
{
RequestCode = requestCode;
}

public void SetResult(Result resultCode, Intent data)
{
ResultCode = resultCode;
Data = data;
}

public void Complete()
{
_taskCompletionSource.SetResult(this);
}
}

#endregion
}

Now let’s take a quick tour and see how this all works. First, there are two overloads of StartActivityForResultAsync. One takes a type of Activity as a generic argument because it’s very common to want to start a new Activity in-process and just refer to it by its type. The other one takes an Intent, which is more flexible. You will typically use this variant for out-of-process activities.

These methods also take an optional CancellationToken, which can be used to cancel the launched Activity. If the token is cancelled then the code that is waiting on the async result will get a ResultCode that indicates that it was cancelled.

Both of those methods call into the same core routine that sets up the bookkeeping. It is responsible for creating the object that tracks the results and returning the Task that we can wait on.

Once the Activity has been started we return the Task object to the caller, and then we wait for a call to OnActivityResult. If you recall from part one of this series, that method call is actually forwarded to us by our FragmentActivity class (in the Android SDK there is no OnActivityResult method in Fragment, but we added one for this purpose). In OnActivityResult we check to see if the request code is one that is in our Dictionary of pending async activities. If it is then we record the ResultCode and the Intent, add it to a list of finished results, and then remove the item from our Dictionary. Later we will get a call to OnResume, which just goes through the list of finished results and calls the Complete method. That is the method that actually pushes the results into the TaskCompletionSource (by calling SetResult), which unblocks anything waiting on the Task.

And that’s it. Now we have enough to start a new Activity and wait for its result in a single, small function. I have posted a full version of the code with a small example app on GitHub.

Summary

So far in the first two parts of this series I have covered how to preserve state across configuration changes and how to simplify the process of starting new activities and waiting for their results. With those two challenges solved we can avoid a lot of ugly boilerplate code. However, there is still one significant source of tedious boilerplate code: communicating between these activities still has to be done through Intent objects. In the next part of this series I will extend this code even further to allow for directly accessing the new Fragment object for in-process activities.