Menu

Toehold Test

Let’s write a small class that has potential to grow.

data class ZipCode(val code: String) {  
  init {
    require(code.matches(Regex("""\d{5}"""))) {
      "not a zip code: $code"
    }
  }
}

Should you write a unit test for this? Turbo test-driven developers do because they obsess over test coverage and test everything! But what about us pragmatic developers who are in a hurry, and who aren’t obligated by process?

I claim that we should! Not to defend against regressions, but instead to serve as a toehold for further tests. Someday somebody may extend this and it’ll be helpful to have a test to build upon.

This is particularly worthwhile when the test requires setup. If your obviously-correct code needs a fake clock or a temporary directory to be tested, the toehold-test’s job is to configure that stuff. That way there’s no friction to testing when it’s most useful.

If you need inspiration, name the toehold test happyPath()!

Deadlines

My recent work requires coordinating teams to build their own pieces of a larger puzzle. We’re going to replace old system 𝒂 with new systems 𝔁, 𝔂, and 𝒛, and that means each team needs to land their contribution on schedule.

But in my heart I know that software hates schedules! We’re inventing as we go and all kinds of risks can wreck the timeline. Here’s some recent ones that impacted my team:

  • A critical team member left the company.
  • A Java 8 bug blocked feature development ’til we upgraded to Java 11.
  • Random packet loss between our datacenter and AWS blocked migration.

How do we coordinate anything done with so much uncertainty?!

This clarified things for me: Deadlines aren’t predictions; they’re constraints. Software projects are elastic in scope. Replace “when will the whole thing be done?” with “how much can we land by April?”

I’m still uncomfortable going more than a few months into the future. That’s when the risks compound!

Live Forever

I don’t have a fountain of youth but instead a surprising approximation. You know the expression, “time flies while you’re having fun?” It’s almost right. Your brain’s perception of time flies when you’re doing something familiar. And most importantly, your perception of time slows when you’re doing something new and novel.

Belle Beth Cooper’s post explains this idea further. Try new uncomfortable things and live a rich life!

Weightloss

If you lose 10 pounds, where do those pounds go? It’s weird trivia that I never learned in school. Do you poop it out? pee? sweat?

A parallel question clarifies: where does the gasoline goes when you drive your car? The car’s internal combustion engine turns oxygen and petrol into energy and CO₂. The air leaving a car’s muffler is heavier than the air that entered its radiator! This is unintuitive because air seems so... weightless.

Your body works the same way. You convert oxygen and calories into energy and CO₂. Breathing while you sleep means you’ll weigh less waking up than you did falling asleep! And aerobic exercise runs the process harder so naturally it burns more calories.

NPR has details on the process. I find it all fascinating.

SQL Multiple-Column IN Clause

The IN clause is handy. I use it all of the time.

SELECT  
  * 
FROM  
  cars
WHERE  
  make IN ('Ford', 'Subaru') AND
  price < 5000;

+--------+---------+------+--------+-------+
| make   | model   | year | color  | price |
+--------+---------+------+--------+-------+
| Ford   | Focus   | 2007 | Black  |  1100 |
| Ford   | Mustang | 2005 | Yellow |  4000 |
| Ford   | Fiesta  | 2011 | Yellow |  4500 |
| Subaru | Legacy  | 2003 | Yellow |   900 |
| Subaru | Impreza | 2005 | Red    |  1400 |
+--------+---------+------+--------+-------+

Today I came across a two-column IN clause in a code review:

SELECT  
  * 
FROM  
  cars
WHERE  
  (make, color) IN (
    ('Ford', 'Yellow'), 
    ('Subaru', 'Red')
  ) AND
  price < 5000;

+--------+---------+------+--------+-------+
| make   | model   | year | color  | price |
+--------+---------+------+--------+-------+
| Ford   | Mustang | 2005 | Yellow |  4000 |
| Ford   | Fiesta  | 2011 | Yellow |  4500 |
| Subaru | Impreza | 2005 | Red    |  1400 |
+--------+---------+------+--------+-------+

How’d I go my whole life without this? Good stuff.

Developer Identity & Multiplatform

We don’t self-identify as software developers but as web developers, backend developers, Android developers, or iOS developers. Many factors reinforce this specialization.

I’m a Droid

Building systems builds experience. Android developers learn technologies that have no analog on other platforms: activities, intents, and XML layouts. Once we’ve mastered the quirks of Android’s lifecycles that’s a superpower for writing even more Android code.

We build communities around these common skills. We’ve got conferences, meetups, Slack channels, and open source. These communities aren’t strictly technical; we also make friends and even get jobs through them.

And we’ve been tribal. Years ago it wasn’t clear how many mobile platforms would thrive. Windows Mobile, Palm, and Blackberry all had a chance. We didn’t want to develop for iPhone’s confined sandbox. Android is open!

iOS and Android have Converged

Our steady state is iOS and Android. Kotlin and Swift are more similar than Java and Objective-C. Our UIs were flattened and we’ve even stopped complaining about apps that look like iOS.

But our two platform steady-state sucks. Product teams have to build everything twice. Not only do the two apps need to work,

URL Encoding Is Material

Lots of OkHttp and Retrofit users have reported bugs complaining that URL special characters (like + ; | = * ; ; | or *) weren’t encoded as they expected.

Why can’t HttpUrl just encode ; as %3B?

Extra escaping is safe in most programming languages and document formats. For example, in HTML there’s no behavior consequence to replace a non-delimiter " character with its escape sequence &quot;. Or in JSON, it’s safe to replace the string "A" with "\u0041".

But URLs are different because URL encoding is semantic: you cannot encode a URL without changing it. This is weird!

Too Much Encoding

Suppose we’re looking up 100% on DuckDuckGo. Since the code point for % is 0x25, that character encodes as %25 and the whole URL is https://duckduckgo.com/?q=100%25.

But what if we encode the already-encoded URL of that query? We would double-encode the % as %2525 and end up searching for 100%25. Yuck: https://duckduckgo.com/?q=100%2525.

Too Little Encoding

Next we’ll search for #1 on Google. We’ll encode # as %23 and get this URL: https://www.google.ca/search?q=%231.

What if we forget to encode the # in the query? Since # is used as

A Clever, Flawed OkHttp Interceptor Hack

All of OkHttp’s configuration is on the OkHttpClient instance:

OkHttpClient client = new OkHttpClient.Builder()  
    .readTimeout(2_000, TimeUnit.MILLISECONDS)
    .writeTimeout(2_000, TimeUnit.MILLISECONDS)
    .cache(new Cache(cacheDirectory, cacheSize))
    .build();

This design is minimal and simple. There aren’t any precedence rules or hidden settings to be surprised by. To customize a particular option for a particular call, derive a new client from an existing one:

OkHttpClient longTimeoutClient = client.newBuilder()  
    .readTimeout(60_000, TimeUnit.MILLISECONDS)
    .writeTimeout(60_000, TimeUnit.MILLISECONDS)
    .build();

This minimal API feels too simple when the OkHttpClient instance is encapsulated within another framework. For example, consider Retrofit:

OkHttpClient client = ...  
Retrofit retrofit = new Retrofit.Builder()  
    .baseUrl(serverBaseUrl)
    .callFactory(client)
    .build();
EmojiService emojiService = retrofit.create(EmojiService.class);  

To extend the timeout for one endpoint I need to create a new OkHttpClient, a new Retrofit, and a new EmojiService. Ick. We’re planning a proper fix for this. But until that’s ready, there’s this ridiculous other thing you can do.

public class CheatingInterceptor implements Interceptor {  
  volatile OkHttpClient clientOverride;

  @Override public Response intercept(Chain chain)
      throws IOException {
    OkHttpClient override = clientOverride;
    if (override != null) {
      return override.newCall(chain.request()).execute();
    }

    return chain.proceed(chain.request());
  }
}

This interceptor breaks the

Canonical URLs for Javadocs

We publish separate Javadocs for each major release of OkHttp: 1.x, 2.x, 3.x. This is intended to help you out when you’re using an old version. But it’s had an adverse side-effect: Googling for “responsebody okhttp” only returns results for old versions. You see the same problem when you search for “LinkedHashMap” and get Java 7 instead of Java 8.

On Paul’s recommendation, a couple weeks ago I updated the old version’s docs to point at their modern counterparts with a canonical URL tag:

<link rel="canonical" href="https://square.github.io/okhttp/3.x/okhttp/okhttp3/ResponseBody.html"/>  

Google has since reindexed our docs and now it prefers the current versions in query results. Nice.

https://google.com/search?q=responsebody+okhttp

Story Code

Designing APIs is hard. One technique that helps me is to tell a story with the code: I’ll make a sequence of calls to show how things fit together. I find this helps me to discover what methods I need and what I can leave out. Using features together shows me how they integrate and reveals inconsistencies in naming and behavior.

Where does this exploration live? Usually I just sketch it out in IntelliJ as a main method or test case. For example, to build the API for a parking meter I might start with this:

public final class ParkingMeterTest {  
  FakeClock clock = new FakeClock();
  ParkingMeter parkingMeter = new ParkingMeter(clock);

  @Test public void testParkingMeter() {
    // This meter charges 25 cents for 15 minutes.
    parkingMeter.setRate(25, 15);
    parkingMeter.setMaxTime(60);

    // Initially the parking meter is expired.
    assertEquals("00:00", parkingMeter.display());
    assertTrue(parkingMeter.isExpired());

    // A customer puts in 50 cents to get 30 minutes.
    parkingMeter.addMoney(50);
    assertEquals("00:30", parkingMeter.display());
    assertFalse(parkingMeter.isExpired());

    // After 29 minutes elapses there's still one minute left.
    clock.advance(29, TimeUnit.MINUTES);
    assertEquals("00:01", parkingMeter.display());
    assertFalse(parkingMeter.isExpired());

    // After 1 more minute the meter is expired.
    clock.advance(1, TimeUnit.MINUTES);
    assertEquals(

Name Your Threads

I work on a big Java service that does lots of things. When I snapshot the application’s threads I can see it’s got lots going on:

  • Talking RPC and HTTP
  • Running cron jobs and job queue jobs
  • Persisting to MySQL
  • Coordinating with ZooKeeper
  • Collecting garbage

At a glance I can see what the service is doing: what’s blocked on I/O, what’s executing, what’s waiting for locks, and what’s idle.

Analysis is easier if the threads have descriptive names:

  • connection-mgmt-[twilio.com:443]
  • job-queue-outgoing-email-0
  • zk-lb-lease/publisher-outgoing_sms-0

And it’s difficult otherwise:

  • pool-1-thread-3
  • pool-21-thread-99
  • pool-2-thread-1

Naming Threads

The best names help you to know out which class started the thread (connection-mgmt) and what that thread is currently doing (twilio.com:443).

If you’re using Guava, just use ThreadFactoryBuilder. Otherwise use this:

public static ThreadFactory threadFactory(  
    final String name, final boolean daemon) {
  return new ThreadFactory() {
    @Override public Thread newThread(Runnable runnable) {
      Thread result = new Thread(runnable, name);
      result.setDaemon(daemon);
      return result;
    }
  };
}

When your runnable has more context than it’s shared executor, you can use something like OkHttp’s NamedRunnable:

executor.execute(new NamedRunnable("OkHttp Window Update %s", hostname) {  
  @Override public void execute(

Seductive Code

It’s careful work balancing tradeoffs when writing code and designing APIs. Here’s some everyday Java code:

for (Protocol protocol : protocols) {  
  if (protocol != Protocol.HTTP_1_0) {
    result.writeByte(protocol.toString().length());
    result.writeUtf8(protocol.toString());
  }
}

On Android—where garbage collector costs aren’t necessarily negligible—I make my code slightly uglier to save an implicit Iterator allocation:

for (int i = 0, size = protocols.size(); i < size; i++) {  
  Protocol protocol = protocols.get(i);
  if (protocol != Protocol.HTTP_1_0) {
    result.writeByte(protocol.toString().length());
    result.writeUtf8(protocol.toString());
  }
}

Java 8 invites me to make the opposite tradeoff: to use streams and lambdas like a functional programmer:

protocols.stream()  
    .filter(protocol -> protocol != Protocol.HTTP_1_0)
    .forEach(protocol -> {
      result.writeByte(protocol.toString().length());
      result.writeUtf8(protocol.toString());
    });

Here we’ve got three perfectly-reasonable ways to write the same code, and therefore the perfect opportunity to have a disagreement on how this loop should be written.

When a programming language, API, or design pattern is seductive its cosmetic beauty hides its structural limitations. I’m frustrated when making my code read better harms how efficiently it runs or how maintainable it is.

Seductive and Slow

Recently

Jesse, Learning in Anger

I’m using an open source library and it crashes in an unexpected way. The crash makes me grumpy because it prevents me from getting my real work done.

I don’t want anyone to face this indignity ever again! And so I proceed to report the bug to the library’s maintainers. Since I’m grumpy it’s not enough to say “your shit’s broke”. I have to make it crystal clear how and where it’s broken. I need to shame them for writing imperfect code.

So I attempt to write the simplest program that demonstrates this insidious bug. I start with my initial codebase with all of its moving parts. I attempt to remove distractions and unrelated features until all I’m left with is a trigger for the bug.

But as a side effect of isolating the bug I end up learning the internals of this library that I’d previously been treating as a black box. Studying this program in anger has the same effects as studying anything: I learn it.

I learn why their code is complicated. Over here it’s because in 2011 they had to workaround a bug in the Eclipse

Charles 4 has HTTP/2

Karl von Randow has released Charles 4.

“With Charles 4 you can now see HTTP 2 working, and you can use all of your familiar tools; Repeat, Breakpoints, and so on. You’ll spot HTTP 2 hosts in Charles as they use a different icon—with a lightning bolt!”

I just took it for a quick spin. The updated HTTP/2 support works as advertised.

If you’d like to try out Charles new HTTP/2 support with OkHttp, it’s three steps to configure OkHttp to trust Charles’ MITM certificate.

Export the certificate from Charles

From the Help menu, pick SSL Proxying and then Save Charles Root Certificate. Save it as a .pem file somewhere, then open it in your favorite text editor. You’ll see something like this:

-----BEGIN CERTIFICATE-----
MIIFfDCCBGSgAwIBAgIGAU9cHuWJMA0GCSqGSIb  
IFByb3h5IEN1c3RvbSBSb290IENlcnRpZmljYXR  
...
ieHLSeZtdIrL7cI45ILT4TkahmPVeZmVVCRwQ==  
-----END CERTIFICATE-----

Import the certificate into OkHttp

OkHttp has an executable custom trust example that we’ll start with. Remove the example’s certificates. Paste the contents of the .pem file instead.

  private InputStream trustedCertificatesInputStream() {
    String charlesRootCa = ""
        + "-----BEGIN CERTIFICATE-----\n"
        + "MIIFfDCCBGSgAwIBAgIGAU9cHuWJMA0GCSqGSIb\n"
        + "IFByb3h5IEN1c3RvbSBSb290IENlcnRpZmljYXR\n"
        + "...\n"
        + "ieHLSeZtdIrL7cI45ILT4TkahmPVeZmVVCRwQ==\n"
        + "-----END CERTIFICATE-----\n";
    return new Buffer()
        .writeUtf8(charlesRootCa)
        .inputStream();
  }

Point OkHttp at the Proxy

The custom trust example

Java’s new HTTP client is upside down

One of Java 9’s new features is a replacement for HttpURLConnection. And while I’m thrilled to get rid of that old garbage its replacement has its own surprises.

The Good

The API is small. The new package is java.net.http and the Javadoc shows only 12 new HTTP types plus 6 more for websockets.

It implements HTTP/2. There’s NIO and java.util.concurrent APIs throughout so it might be efficient for many parallel requests.

There’s builders! And an HttpClient type. Java’s built in TLS stack has been upgraded to support ALPN which means it can negotiate HTTP/2 without the awkward jetty-alpn bootclasspath trick.

The Bad

There’s an HttpHeaders type, but it’s an interface and not an immutable value object. There’s no builder for the headers, only for the HttpRequest.

Though HttpURLConnection is now unnecessary, this new client continues to rely on several of its obsolete support classes. The most frustrating of these is URI, which can’t represent real-world URLs such as those in Google’s image charts. And if you want query parameters you have to concatenate strings.

Many useful knobs and features are absent from the API.

The Last HttpURLConnection

An awkward API

OkHttp 1.0 started out as an optimized implementation of HttpURLConnection. This old API is awkward to implement because there is an implicit state machine that corresponds to the underlying network I/O.

GET / HTTP/1.1  
Host: publicobject.com  
Accept: text/html

HTTP/1.1 200 OK  
Content-Length: 300

<html>  
<head><title>Public Object</title></head>  
...

For example, calling getResponseCode() forbids future calls to setRequestProperty() because request headers can’t be edited after they’ve been transmitted.

HttpURLConnection connection = urlFactory.open(url);  
int responseCode = connection.getResponseCode();

// This fails with an exception at runtime!
connection.setRequestProperty("Accept", "text/html");  

What’s safe to call is especially awkward because the state machine itself is dynamic: setFixedLengthStreamingMode() and setChunkedStreamingMode() cause request body writes to lock in request headers.

An uncomfortable implementation

With OkHttp 2.0 we introduced a new API to complement HttpURLConnection. Instead of an implicit state machine the new API uses types to make an explicit model: Request has the inputs, Response has the outputs, and Call does the action.

Request request = new Request.Builder()  
    .url(url)
    .header("Accept", "text/html")
    .build();

Call call = client.newCall(request)

The Open Source Maintainer’s Dilemma

We’re in a golden age of reusable open source code. With GitHub and Maven Central it’s never been easier to create and share code.

This is excellent! Android developers have access to a steady stream of new projects. I keep up by following some Android developers on Twitter and by subscribing to Android Weekly and #AndroidDev Digest.

Releasing a new open source project is fun. Take your most reusable code, polish it off, and publish it to the world! Give back to the development community and earn your reputation.

Free as in puppy

There’s a catch. When you release an open source library you implicitly volunteer to be the ongoing maintainer of that library. It’s an unpaid job that imposes real time commitments.

The work as maintainer is to earn trust. This comes by implementing features, fixing bugs, answering Stack Overflow questions, and by responding to (often inane) GitHub issues. If you succeed your userbase will grow and hopefully it’s mostly fun.

Another option is to not do the work. This feels bad in the same way that ignoring street poverty feels bad. Users of my code ask me for things “Please help with this

Disable Cleartext in OkHttp

Alex Klyubin posted instructions on disabling cleartext networking in Android’s built-in HTTP stack.

Ideally, your app should use secure traffic only, such as by using HTTPS instead of HTTP. Such traffic is protected against eavesdropping and tampering.

Unfortunately that approach requires Android 6 or better. But if you’re using OkHttp you can disable cleartext networking for all versions of Android. Just configure your client’s connection specs:

OkHttpClient client = new OkHttpClient.Builder()  
    .connectionSpecs(Arrays.asList(
        ConnectionSpec.MODERN_TLS,
        ConnectionSpec.COMPATIBLE_TLS))
    .build();

If you want even more control, the HTTPS page on OkHttp’s wiki shows you how.

Deliberate Disobedience

Some friends and I do regular boardgame nights. Our favorite is Tichu. The first few times we played we got the rules wrong: we thought certain plays were legal but they weren’t. By playing more, studying the rules, and Googling the edge cases, we eventually got the rules right. We played the right way for a long time! But after years of doing it by the book we came to agree that one of the rules made the game worse. So collectively we decided to ignore it! And we’ve been enjoying Tichu immensely ever since.

Our understanding of Tichu followed this progression:

  1. Fail to follow the rules because we don’t know them.
  2. Strictly follow the rules.
  3. Deeply understand the rules and deliberately disobey the one we don’t like.

Though we aren’t following the rules in either the first or third cases, the reasons why are quite different. #1 comes from a lack of understanding while #3 comes from an abundance of it. I’ve seen this pattern elsewhere.

Coding

Software developers have no shortage of guidelines to follow spanning all aspects of our craft. Some favorites are Effective Java, Google’s Java Style Guidelines, and

Reflection-friendly Value Objects

There’s plenty of good advice on how to do value objects well in Java. Ryan Harter’s AutoValue intro is particularly handy.

When I’m not using AutoValue, I like to do my builders as recommended in Item 2 of Effective Java Second Edition. In it Josh Bloch recommends a private constructor that accepts the Builder as a constructor parameter:

public final class Pizza {  
  public final Size size;
  public final List<Topping> toppings;
  public final Cheese cheese;

  private Pizza(Builder builder) {
    this.size = builder.size;
    this.toppings = immutableList(builder.toppings);
    this.cheese = builder.cheese;
  }

  public static final class Builder {
    private Size size = Size.MEDIUM;
    private List<Topping> toppings = new ArrayList<>();
    private Cheese cheese = Cheese.MOZZA;

    // …setters…

    public Pizza build() {
      return new Pizza(this);
    }
  }
}

This example also assigns default values in the builder. But these defaults are lost when Moshi or Gson use reflection to decode a pizza from JSON. This problem is explained in Moshi’s readme:

If the class doesn’t have a no-arguments constructor, Moshi can’t assign the field’s default value, even if it’s specified in the field declaration. Instead, the field’s default is always 0 for

Reflection Machines

Conventional wisdom says that reflection is slow and that it should be avoided. As always, the truth is more nuanced.

Let’s start with some code.

class Movie {  
  static final List<Movie> BEST_MOVIES = Arrays.asList(
      new Movie("Back to the Future", 1985),
      new Movie("Back to the Future 2", 1989),
      new Movie("Jurassic Park", 1993),
      new Movie("Starship Troopers", 1997));

  final String name;
  final int releaseYear;

  public Movie(String name, int releaseYear) {
    this.name = name;
    this.releaseYear = releaseYear;
  }
}

We’ve got a movie class. Next we’ll write some gratuitous reflection. How about a logging API with reflection-based string interpolation?

  for (Movie movie : Movie.BEST_MOVIES) {
    FancyLogger.log("I loved $name. Did it win best picture in $releaseYear?!", movie);
  }

The hasty implementation is easy:

public final class FancyLogger {  
  public static void log(String message, Object value) {
    try {
      for (Field field : value.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        String fieldValue = String.valueOf(field.get(value));
        message = message.replaceAll("\\$" + field.getName(), fieldValue);
      }
      System.out.println(message);
    } catch (IllegalAccessException e) {
      throw new AssertionError(e);
    }
  }
}

Unfortunately, the code above is why reflection is slow. The problem isn’t that we’re doing reflection, but that we’re doing reflection every single time

Ceilings & Floors

I’ve been thinking about policies and incentives. A lot of motivation comes down to ceilings and floors.

  • Floors: the worst case. We want to raise the floor, limiting the pain in the worst case. Minimum wage is a floor on labor.
  • Ceilings: the best case. We also want to raise the ceiling, improving the pleasure of the best case. A company that expands into new countries raises the ceiling on how many customers they can reach.

Once I start thinking in these terms, they appear everywhere.

Performance Tradeoffs in UTF-8 encoding

In Okio we implemented our own UTF-8 encoder to save the overhead of allocating byte arrays. The encoder was faster for most strings, but not very long ones.

By switching to our own UTF-8 encoder, we made the fastest case faster (raising the ceiling) but made the slowest case slower (lowering the floor).

Security tradeoffs in web session duration

Sign into any website and measure how long it takes for your session to expire. At my bank, the sessions are painfully short, like 60 minutes or less. On Pocket my web session seems to last forever.

Here the short session raises the floor on my security, making session

OkHttp Certificate Pinning Vulnerability!

Bad news. When I added certificate pinning in OkHttp 2.1, I didn’t sanitize the server’s certificate chain. An attacker could exploit this weakness to defeat the protection offered by certificate pinning.

The vulnerability was disclosed to Square by security researcher John Kozyrakis. Whew! We fixed it in OkHttp 3.1.2, and backported that to OkHttp 2.7.4. Matthew McPherrin has requested a CVE for this vulnerability.

If you’re using OkHttp, you should upgrade to the latest version immediately! Staying up to date on OkHttp is a good idea – we track the latest HTTPS cipher suites & TLS versions to balance connectivity with security. It’s like keeping the browser up to date on your computer: staying current is the best way to stay safe.

LinkedHashMap is always better than HashMap

Deterministic code is much easier to debug & understand than non-determinstic code. Got a test that’s failing? Launch the debugger, step through the code, and find the exact statement where an assumption is violated. For me this often looks like a binary search. I add breakpoints and make assertions like “everything is fine before we call pruneCache()”. I’ll run the app, learn something, and repeat.

When you use HashMap in your programs, you’re introducing needless nondeterminism. This is because HashMap’s iteration order is different between platforms (Android vs. Java) and between executions for classes that don’t override equals() and hashCode().

This nondeterminism is toxic to debugging. I think it’s even worse than the nondeterminism caused by multithreading because it’s so unexpected.

Does this program always return the same result?

private static float massPerUnit(  
    float totalMass, float w, float h, float d) {
  Map<CharSequence, Float> dimensions = new HashMap<>();
  dimensions.put(dimension("width", "x"), w);
  dimensions.put(dimension("height", "y"), h);
  dimensions.put(dimension("depth", "z"), d);

  float massPerUnit = totalMass;
  for (Float dimension : dimensions.values()) {
    massPerUnit /= dimension;
  }

  return massPerUnit;
}

Surprise, it doesn’t. And HashMap’s non-deterministic iteration order is to

Your strict naming conventions are a liability

Programmers tend to be pretty obsessive over consistency. Most of that consistency is worthwhile, but some of it is foolish.

For example, let’s take some JSON from GitHub’s gists API:

{
  "files": {
    "Hello.txt": {
      "type": "text/plain",
      "content": "Hello World!\n"
    }
  },
  "created_at": "2014-05-27T02:31:35Z",
  "updated_at": "2015-08-29T14:01:51Z"
}

And we’ll map this JSON structure to some Java classes:

public final class Gist {  
  Map<String, GistFile> files;
  Date createdAt;
  Date updatedAt;
}
public final class GistFile {  
  String type;
  String content;
}

It’s light work for Gson to decode the document into a Java objects:

Gist gist = gson.fromJson(json, Gist.class);  

And moments later, heartbreak! Because createdAt and updatedAt fields are both null! The problem of course is that these field names are camelCase in Java (createdAt) vs. snake_case in JSON (created_at).

Well that sucks. We’ve got three bad choices.

Choice 1: Get the framework to flex its muscle

Gson has built-in magic to convert snakes into camels with its LOWER_CASE_WITH_UNDERSCORES FieldNamingPolicy. We make a global configuration change to our Gson instance and the problem is solved.

Gson gson = new GsonBuilder()  
    .setFieldNamingPolicy(LOWER_CASE_WITH_UNDERSCORES)
    .create();

Choice 2:

Sneaking Data into an OkHttp Interceptor

OkHttp Interceptors are a fun & powerful way to implement cross-cutting behavior in your app. You can use ’em for authentication, performance, monitoring, and more. There’s even open source interceptors for OAuth signing and curl logging!

Suppose we want to write an interceptor that tracks which activities use the network the most. For each HTTP call we’ll measure how big it is, how long it took, and which activity triggered it:

public final class CallMeasurement {  
  long requestSize;
  long responseSize;
  long requestDurationMillis;
  long responseDurationMillis;
  String activityName;
}

Our interceptor watches all calls & measures them:

public final class MeasuringInterceptor implements Interceptor {  
  final List<CallMeasurement> measurements = new ArrayList<>();

  @Override public Response intercept(Chain chain) {
    ...
  }
}

We have a problem: there’s no obvious way for the interceptor to find out which activity triggered the call. We could cheat by doing pattern matching on the URLs, or by looking at which activity is in the foreground, but both are clumsy and could be unreliable.

It turns out that we can sneak data into an interceptor with a request header! When initiating each request, include a header that contains the data of interest:

Request request = new Request.Builder()  
    .url("...")
    .header(

The Play Store is bad at their job

Today Google removed Podcast Addict from the Play Store. Sometimes people publish podcasts containing sexually explicit material, and Podcast Addict is capable of accessing such material.

“Podcast Addict was the #1 podcast app on the Play Store with 4M downloads, 175K reviews and an average rating of 4.6/5 The app almost had 500K daily users and more than 1M episodes were listened to everyday through the app...”

So the Play Store prevents podcast listeners from using a popular podcasting app.

Last week I discovered that my app, Shush Ringer Restorer has an unauthorized clone in the Play Store. That app has the same exact name as my app, which I assume is in an attempt at tricking users into downloading the wrong app. I petitioned Google to take down this lookalike app, with links to all the media attention Shush has received.

They declined because I haven’t registered a trademark:

“Thanks for submitting your trademark complaint, dated 01/04/2015. We will not be taking action against the apps in question at this time as we are unable to ascertain the validity of your trademark rights. If you'd like us to investigate further, please send us evidence

4 Brainy Books

Like books? I don’t have the attention span for reading but I listen to plenty of audiobooks. Here are some of my all-time favorites.

On Intelligence

Non-fiction by Jeff Hawkins

How your brain works.
Amazon, Audible

Daemon

Fiction by Daniel Suarez

In Terminator, Skynet just launches the nukes. In Daemon, the AI is much better: it uses coercion!
Amazon, Audible

Antifragile

Non-fiction by Nassim Nicholas Taleb

Feedback loops and failure.
Amazon, Audible

The Martian

Fiction by Andy Weir

“I'm gonna have to science the shit out of this.”
Amazon, Audible

OkUrlFactory is going away

OkHttp exposes three APIs:

  • Request/Response. This is the most fully-featured API. It can be used synchronously or asynchronously. It avoids mutable state. Plus interceptors!
  • OkUrlFactory, the HttpURLConnection API. This is a complete implementation of an awkward API. The API’s awkardness has resulted in an implementation that is complex and fragile.
  • The Apache HTTP client shim. This is intended to simplify migration. It’s a partial implementation; some methods throw UnsupportedOperationException when invoked.

In OkHttp 3.0, we’re deprecating both OkUrlFactory and Apache HTTP client shim. And we’ll be deleting them in a follow-up release.

If you’re using the Request/Response API, this is good news. It means we’ll be able to significantly simplify the OkHttp internals yielding better performance and stability.

If you’re using OkUrlFactory this is good news. Finally an excuse to shed some of your own tech debt and adopt a better API. Did I mention interceptors?! If for whatever reason you can’t upgrade, you’ll need to rely on the platform’s built-in HttpURLConnection going forward.

And if you’re on the Apache HTTP client shim, this is merely annoying. You can make your own shim by forking ours

com.squareup.okhttp3

We’re about to start working on OkHttp 3.0. It’ll be like OkHttp 2.7, but with small backwards-incompatible API changes. For example, we’re going to make multipart better.

How can we roll this out without breaking everything? As Jake explains, we’re going to cheat! By changing the package name and Maven group ID, you’ll be able to have both OkHttp 2.7 and OkHttp 3.0 in the same app at the same time.

Shipping two copies of a library is a terrible long-term solution! It bloats your app, consumes more memory, and exacerbates the 65K dex limit. But it’ll enable you to update OkHttp in your application independently from its libraries. Preferably you can get everything upgraded by the time you release your app.

Note that our approach is quite different from Guava’s versioning philosophy. Our package renames will require you to find & replace imports – how annoying! But it also means we can change things without a drawn out deprecation period. Like ripping off the band-aid!

We’re doing this for both OkHttp 3 and Retrofit 2. I’m looking forward to both.