Basic HTTP/1.1 with Okio

In a post on The Corner on Wednesday I claimed that OkHttp is one of the most challenging projects I've worked on. Here's the proof that I was lying: an HTTP request in 12 lines of code.     Socket socket = new Socket("square.com", 80);     BufferedSink sink = Okio.buffer(…

10 things you can do with Okio's ByteString

// Decode base64.     ByteString a = ByteString.decodeBase64("bWFwbGUgc3lydXA=");     // Encode base64.     String b = a.base64();     // Decode hex.     ByteString c = ByteString.decodeHex("776166666c6573");     // Encode hex.     String d = c.hex();     // Read from an input stream.     ByteString e = ByteString.read(new FileInputStream("foo.txt"), 50);     // Write to an output…

Satisfying improvements

My post on The Corner today: “The most satisfying improvements are the ones that simultaneously speed up the code, simplify the implementation, and improve the API. In this post I'll describe an ugly situation that led to one of these solutions.”…

Discrimination isn't always intentional

I know I'm guilty of some biases listed here, such as stereotyping job role based on gender. It requires a conscious effort to be inclusive, but it's an effort worth making.…

The computer you wear

Smart watch: the computer you wear Smart phone: the computer in your pocket Tablet: the computer for your coffee table Laptop: the computer you take to work Desktop: the stationary computer I don't use my tablet because the niche between phone and laptop isn't big enough. I think the niche…

OkBuffer Preview

I spent my weekend hacking on OkBuffer, an unbounded byte buffer that reads at the front and writes at the back. Unlike NIO buffers, you never need to flip this thing!…

KB on Code Reviews

Kevin Bourrillion on AMA: “Nothing is more important than reviewing each other's code”…

Edit Bookmarklet

Makes any webpage instantly editable. Use it to redact private information before taking a screenshot. Or to preview what new text will look like in a UI. Or for pranks. javascript:document.body.contentEditable = 'true'; document.designMode='on'; void 0…

3 highlights and 1 lowlight of Google's Java Style Guide

Google employs thousands of Java programmers that collectively maintain many millions of lines of Java code. So they need a comprehensive style guide to quickly resolve any dispute. It's a brilliant document that succinctly and unambiguously describes how to write stylish Java code . Highlight: UTF-8 encoding Googlers aren't limited to…

In KitKat, some reflection is implemented in Java

The newly-released Android KitKat source shows that some of the java.lang.reflect package is implemented with regular Java code. For example, the method that looks up annotations can parse its own dex file. It's turtles all the way down.…

The Tick

To a human the computer's clock is fluid, constantly running through imperceptibly-brief milliseconds. But to the CPU, clock changes are rare events. You can run lots and lots of code between clock ticks. High-precision timers tick more frequently, but they don't solve the problem. How many distinct timestamps should I…

Waterloo's new startup neighbourhood has a parking problem

Waterloo's new startup neighbourhood has a parking problem. Anthony Reinhart argues that it's time to break with car culture: "Free and cheap parking – and huge parking lots, often with empty spaces – were everywhere, even downtown. People drove everywhere, even just a few blocks, often alone in their cars. And…

iDraw is vector drawing tool for the Mac

iDraw is vector drawing tool for the Mac. It's powerful and fast, with a gentle learning curve. It filled the hole in my heart previously filled by CorelDRAW and then Lineform. For $25 it's also a great value. Especially when compared to CorelDRAW which priced at $500 in 1993 (!), and…

Wire Protocol Buffers

At Square we like protocol buffers because the schemas make it easy to share data between client server teams. But the Java code that protoc generates is both heavyweight and ugly. So we created Wire, a new protocol buffer library for Android and Java. To get a feel for Wire,…

I want annotated stack traces!

The message on Java exceptions is very helpful. But even that isn't always enough to diagnose a runtime failure.   java.lang.NullPointerException     at square.cash.Emailer.expired(Emailer.java:348)     at square.cash.Processor.process(Processor.java:99)     at square.queue.Queue.run(Queue.java:251) I'd love to see…

Raise volume above recommended level?

I hate this dialog. It interrupts me, contradicting Android's Design Principles. And it's unkillable, resurrecting itself after every reboot.…

If it's contentious, avoid email.

Simon Stewart: "Bear in mind the hierarchy of communication: nothing -> email group -> email -> IM -> VC -> in person "The further to the right you are […], the quicker misunderstandings can be resolved and design choices made." "The further…

OpenGL is tricky.

I've experimented with OpenGL ES 2.0 every six months or so for the last 2 years. It's been rough. Googling for answers was okay once I already knew my way around. But I was very frustrated in the beginning, especially since every site does things differently. Some sites are…

Some tighter loops

Java 5 for:each loops are the best. But you can't always for:each. Here's three idiomatic loop patterns that I like to use in my code... Bytes in a stream   public void processBytes(InputStream in) throws IOException {     byte[] buffer = new byte[1024];     for (int count; (count = in.read(buffer)…

Free to play

Ramin Shokrizade: “A game of skill is one where your ability to make sound decisions primarily determines your success. A money game is one where your ability to spend money is the primary determinant of your success. [...]. A key skill in deploying a coercive monetization model is to disguise your…

InputStream mark() and reset() are handy, but broken.

The API is limited to saving a single position in a stream. Suppose Picasso marks a position in a bitmap stream, then calls BitmapFactory to process that stream. Since BitmapFactory itself calls mark() and reset(), it clobbers Picasso's mark position and things break when Picasso calls reset(). The Java NIO…

The Stand

Daniel Terdiman: One of the most carefully crafted design elements of Stand is the subtle but satisfying click it makes when it rotates into its home positions at 0 and 180 degrees The snap feels very nice. It reminds me of opening the HTC Dream.…

Charles Nutter on Java 7

Charles Nutter: "So when the child process exits, the any data waiting to be read from its output stream is drained into a buffer. All of it. In memory." Scary stuff.…

Effective Android HTTP

Last week I gave a talk on HTTP & Android at AnDevCon. I talked about the interesting features of HTTP, tools for testing & debugging, and high-level libraries for REST and images. Alongside the code is a small GitHub project with basic code samples exercising HttpURLConnection, Apache HTTP Client, OkHttp,…

ClassLoaderBuilder

Class loaders are a hassle. They like to interfere with metaprogramming projects like Dagger. Even worse, it's awkward to write unit tests that exercise class loading bugs. ClassLoaderBuilder is a dangerously delightful class that lets you create alternate realities and rip worm holes between them. ____ public class ClassLoadingTest { ______ static class…

Is Google Code's Project Hosting a zombie?

I'm invested in Google's open source project hosting. I use it for Guice, Gson, DexMaker, MockWebServer, Shush and several others. I'm using all the features: issues, wikis, downloads. Migrating away will not be easy! But Google has lost interest. They haven't mentioned project hosting on the Google Code blog in…

OkHttp 1.0

"At Square, we want it all: advanced features that work right on every device. We also want to ship new tech without waiting for new Android releases." http://corner.squareup.com/2013/05/announcing-okhttp.html…

On Thread.interrupt() and InterruptedException

Here's the rule I live by: Don't interrupt code that isn't expecting to be interrupted. Throw an AssertionError if you're interrupted and didn't expect to be. Everything else is pain. You don't want to waste time testing that your code recovers from interruptions if they aren't going to happen in…

Interesting HotSpot optimizations

Found an interesting doc that describes some HotSpot optimizations. I found this phrase particularly curious: "...Anonymous classes load and unload faster than named ones..."…

Android and Chrome Together

When I moved from ads to Android, I was shocked at how different Android was from the rest of Google. Android address engineering problems quite differently. Suppose you had a giant, overwhelming engineering problem like "built a web browser" or "build a mobile operating system"... The…

Shush! on MacWorld

Andy Ihnatko, writing for MacWorld.com: "Google doesn’t exert as much control over Android developers as Apple does over iOS developers. This held Android back for its first few years, but in Android 4.1, developer freedom pays serious dividends. [...] When the volume drains to zero, a third-party…

Protocol Buffers on Android

The Facebook folks recently posted about how they went through tremendous effort to squeeze their big fat app into Gingerbread's Dalvik VM.  One of the most fattening things Android apps use is protocol buffers. They were designed & optimized for desktop Java, which is much more forgiving when it comes…

Carried away

Sometimes I get a little carried away with my metaphors... "Other dependency injection tools give you the flexibility of a Swiss Army knife and the cutting power of a chainsaw. But if one tool does manicures and also cuts down forests, it brings with it complexity. The tool is…

Glazed Lists 1.9.0

In 2003 I open sourced a project called Glazed Lists. I don't work on it anymore, so I was delighted to find out that a new version was released today. An open source project wins if it can survive without its creator. The kids today don't know how different things…

limpbizkit@

My Gmail address had some Reddit fun today...…

Rip.java

Rip.java is a grep-style tool I've been using since 2008. I'm not old-school enough for 'sed & awk', but can get a lot done with Rip. Here's how it works... It starts when you have some text, like from a log or command or search. Perhaps it's logcat output:…

Oracle Java vs. OpenJDK

The Java we get from Oracle isn't very good: They bundle Ask.com crapware. There's a petition asking them to stop this. They bundle the Java plug-in (applets), even though the Java sandbox is fundamentally insecure. Applets are dangerous but not useful and I don't want them. They've been slow…

An Open Source Tool Box

Writing polished Android apps is difficult. At Square, we've promoted lots of code from internal-only to open source. Some parts of the process: Scope Our best projects address one problem only, and address it completely. API We make lots of little touches & tweaks. For example, with Android FEST we…

What do digital dice look like?

I've been thinking about adding dice to Rounds. There are already a few dice-rolling apps on the Play Store, but nothing Holo. In this mock-up, the pips would swirl around for a second before falling into order. It's similar to Rounds' spin-the-bottle feature. Dice are tricky: pleasing everyone makes for…

No B Team

I gave a tech talk at Waterloo today. Afterwards a student asked, "Why did you choose Square?" That's complicated. But one thing I really like about Square is that we're small enough—and ambitious enough—that every engineer matters. Get hired here, and you'll be working on one…

Demand UTF-8

Each time you encode characters as bytes, you should do two things: Use UTF-8. Explicitly specify that UTF-8 is your charset. Conversely, whenever you decode bytes to characters, you should also do two things: Confirm that the charset is explicitly set to UTF-8. Use UTF-8. If you're working with data…

Markdown Here

Markdown Here is Adam Pritchard's Chrome extension that makes it foolishly easy to format email. Write the email in Markdown. Press a keyboard shortcut (I use CTRL+ALT+M) The message is rendered in place. I especially love how code snippets look! It uses GitHub Flavored Markdown so syntax highlighting…

Don't use FileReader or FileWriter

FileReader and FileWriter are built-in APIs for writing text to the local filesystem. They're extremely convenient and concise:     FileReader reader = new FileReader(file); Sadly, this code is broken, and there's no way to use FileReader or FileWriter in a way that isn't broken. When these classes were designed in 1997,…

RIP lineform.

My first favourite app was CorelDRAW 3 in 1993. It was totally rad. My fingers memorized all the shortcuts. When I was 14, my big Christmas present was the upgrade to CorelDRAW 5. It came in this giant box with a heavy manual and clipart and everything. I loved all…

I hate apps that fall over on an imperfect network.

I hate apps that fall over on an imperfect network. Trying to post on Google Plus with spotty 3G? It throws away everything. Create a masterpiece in Draw Something a little too far away from the WiFi? The app forgets the drawing completely, without even an apology! As a user,…

On implementing JRuby

Charles Nutter: "It is conceivable that a really good machine can learn our hash algorithm really well, but in the case of string hashing we still have to walk some memory to give us reasonable assurance of unique hash codes. So there's performance sin #1 violated: never read from…

ImmutableBagFactory

In the Java Collections API Design FAQ, Joshua Bloch explains why the API includes optional operations: "Clearly, static (compile time) type checking is highly desirable, and is the norm in Java. We would have supported it if we believed it were feasible. Unfortunately, attempts to achieve this goal cause…

MockWebServer on Android

Last week Eric Denman and I did some long-distance pairing on MockWebServer. If you haven't used it, this is what it looks in your code: // 1. Enqueue a response. MockWebServer server = new MockWebServer(); server.enqueue(new MockResponse().setBody("spicy salsa")); server.play(); // 2. Make a request that retrieves…

Vibration in Shush

Shush has never had vibration but I get requests for it. People wish that vibration was on when volume is restored; others want the device to vibrate while it's muted. It's all strange to me since these settings exist elsewhere on the phone. On my Nexus, there's vibrate-only between silence…

Does it throw?

Uh oh. . . . . public int switchOnEnum() { . . . . . . Dwarf dwarf = Dwarf.SLEEPY; . . . . . . switch (dwarf) { . . . . . . case SLEEPY: . . . . . . . . return 0; . . . . . . default: . . . . . . . . throw new AssertionError("dwarf = " + dwarf); . . . . . . } . . . . } Hint 1: Dwarf is an enum. Hint 2: Dalvik is a lot better today than it was just 2 years ago.…