Android, Rx and Kotlin: a case study

There are countless introductions to Rx and quite a few discussing Rx on Android, so instead of writing another one, I decided to come up with a simple activity and go through the entire exercise of implementing it using Rx and Kotlin. I’m sure you’ll be able to follow these article easily even if you’re not familiar with Kotlin because the syntax is remarkably similar to what you would write if you were using Java 8 (just with fewer semi colons).

The activity

It’s shown at the top of this article. It’s pretty simple while covering some important basics and, as we’ll find out along the way, the devil is in the details. Here is a simple functional specification of this activity:

  • The user types a nick name in an EditText. The activity asks the server if such a name is known and if it is, it returns a user record.
  • At this point, the user can “Add” this person as a friend, which triggers another call to the server to verify that the addition is allowed. The server returns a simple “ok” or “error” if that person can’t be added as a friend.

A few additional details:

  • We want to display a progress bar during all server calls.
  • Since we don’t want to bother the server too much, we only start sending requests for names that have three or more characters (we’ll add to this condition later).

Without Rx

Implementing this activity with “regular” Android practices is straightforward:

  • Add a listener to the EditText so we get notified each time a character is typed.
  • Send a network request with an AsyncTask.
  • When the result comes, update the UI (on the main thread and not in whatever thread AsyncTask ended up running).
  • Enable the “Add friend” button and listen to it, calling the server if pressed to verify that the friend can be added (one more AsyncTask + main thread post tap dance).

This implementation is straightforward but it’s very scattered. You will very likely end up with a lot of empty methods added just to satisfy listener requirements, storing state in fields to communicate between the various asynchronous tasks and making sure your threading model is sound. In other words, a lot of boiler plate, a messy mix of headless and graphical logic and graphical update code spread a bit everywhere.

There is a better way.

Kotlin and Android

I found Kotlin to be a very good match for Android even in the early days but recently, the Kotlin team has really cranked up their support for Android and adding specific functionalities for the platform in their tooling, which makes Kotlin even more of a perfect match for Android.

Kotlin M11 was released about a week ago and it added a functionality that makes the appeal of Kotlin absolutely irresistible for Android: automatically bound resources. Here is how it works.

Suppose you define the following View in your layout activity_search.xml:

<Button ...
    android:id="@+id/addFriendButton"
>

All you need to do is add a special kind of import to your source:

import kotlinx.android.synthetic.activity_search.addFriendButton

and the identifier addFriendButton becomes magically available everywhere in your source, with the proper type. This basically obsoletes ButterKnife/KotterKnife (well, not quite, there’s still OnClick which is pretty nice. Besides, Jake tells me he has something in the works). And if you press Ctrl-b on such an identifier, Android Studio takes you directly to the layout file where that View is defined. Very neat.

The server

For the purpose of this article, I’m just mocking the server. Here is its definition:

trait Server {
    fun findUser(name: String) : Observable<JsonObject>
    fun addFriend(user: User) : Observable<JsonObject>
}

If you think this definition looks a lot like a Retrofit service interface, it’s because it is. If you’re not using Retrofit, you should. Right now, I’ll be mocking this server by returning a set of hardcoded answers and also making each call sleep one second to simulate latency (and so we can see the progress bar on the screen). Note that each call on this interface returns an Observable, so they fit right in with our Rx implementation.

In this example, I hardcoded the server to know about two friends (“cedric” and “jon”) but only “cedric” can be added as a friend.

The Rx mindset

Switching to the Rx mindset requires you to start thinking in terms of event sources (observables) and listeners (subscribers). If this idea doesn’t sound that novel, it’s because it’s not. This model was already being advocated in the book “Design Patterns” in 1994 and even in the early versions of Java twenty years ago (and no doubt you can find traces of it in the literature before that). However, Rx introduces new concepts in this idea that we’ll explore in this series.

So let’s rethink our activity in Rx terms: what are event sources (I’ll use the name “observable” from now on) in this activity?

I can count four observables:

  1. First, we have the EditText: whenever a new character is typed, it emits an event that contains the entire text typed so far. We can emit a new name once we have more than three characters.
  2. Next is the name observable, which calls the server and emits the JsonObject it receives in response.
  3. Next in the chain, we have a “user” Observable, which maps the JsonObject into a User instance with the name and id of that person.
  4. Finally, the “Add friend” button is another observable: if the user presses that button, we make another call to the server with the User we have and we update our UI based on the results.

There are various ways we can break this problem into observables and the final result depends on how you want to handle various tasks, which observables you want to reuse, the threading model you prefer, etc…

Implementation

The “EditText” Observable

Let’s start with our EditText. Its implementation is pretty straightforward:

WidgetObservable.text(editText)
    .doOnNext { e: OnTextChangeEvent ->
        addFriendButton.setEnabled(false)
        loading.setVisibility(View.INVISIBLE)
    }
    .map { e: OnTextChangeEvent -> e.text().toString() }
    .filter { s: String -> s.length() >= 3 }
    .subscribe { s: String -> mNameObservable.onNext(s) }

Let’s go through each line in turn:

  • WidgetObservable turns an ordinary View into an Observable. It’s a wrapper coming from RxAndroid that calls all subscribers with the full text whenever a new character is typed.
  • Next we reset the UI to its default state.
  • The map line converts an OnTextChangeEvent into a string. It’s a purely convenience step, so that the next operators in the chain can deal with the context of the EditText as a String instead of having to repeatedly extract it from the event (e.text().toString() everywhere).
  • Next, if the text is less than three characters long, we stop right there.
  • Finally, we subscribe to the value we have obtained if we have reached this far: a string that's at least three characters long. We pass this string to our name observable.

The "name" Observable

val mNameObservable: BehaviorSubject<String> = BehaviorSubject.create()

A BehaviorSubject is a special kind of Observable that you can send events to after its creation. I like to think of it as an event bus, except that it's focused on a very specific kind of events (as opposed to an event bus that is used to post pretty much anything to). Using a Subject here allows me to create that Observable early and only post new events to it as they come in, which is what we did with the snippet of code above.

Let's see how we use that Observable now, by simply subscribing to it, which means receiving names that have three or more characters in them. All we do is call the server and pass the result to the "user" observable:

mNameObservable
    .subscribe{ s: String ->
        mServer.findUser(s).subscribe { jo: JsonObject ->
            mUserObservable.onNext(jo)
        }
    }

We're not quite done, though: we actually have another subscriber to that Observable:

mNameObservable
    .subscribe { s: String ->
        loading.setVisibility(View.VISIBLE)
    }

We need to let the user know we just issued a network call, so we show the progress bar (this is a suboptimal implementation, this logic should be done at the server level, but we'll save this for later).

Note that I'm intentionally hiding a very important part of this logic in order to stay focused on the topic, and this also explains why we have two separate subscriptions. I explain why at the end of this article.

The "User" Observable

Next, we have the User Observable, which gets notified when the server sends us a response to the query "Does the user named 'foo' exist?":

mUserObservable
    .map { jo: JsonObject ->
        if (mServer.isOk(jo)) {
            User(jo.get("id").getAsString(), jo.get("name").getAsString())
        } else {
            null
        }
    }
    .subscribe { user: User? ->
        addFriendButton.setEnabled(user != null)
        loading.setVisibility(View.INVISIBLE)
        mUser = user
    }

This Observable does two things: it updates our UI and it maps the JsonObject response to our data class User. If the call was a success, we assign this value to the field mUser.

The "Add friend" Observable

Finally, we have the "Add friend" button, which only gets enabled once we have a valid User. If the user presses that button, we issue another call to the server to request that person to be added as a friend and then we update the UI depending on the response:

ViewObservable.clicks(addFriendButton)
    .subscribe { e: OnClickEvent ->
        mServer.addFriend(mUser!!)
            .subscribe { jo: JsonObject ->
                val toastText: String
                if (mServer.isOk(jo)) {
                    toastText = "Friend added id: " + jo.get("id").getAsString()
                    editText.setText("")
                } else {
                    toastText = "ERROR: Friend not added"
                }
                Toast.makeText(this, toastText, Toast.LENGTH_LONG).show();
            }
    }

Stepping back

This is a very different implementation of how you would write the code with regular Android calls, but in the end, it's not just compact but it also divides our entire logic in four very distinct components that interact with each other in very clear ways. This is the macro level. At the micro level, these four components are not just self contained, they are also highly configurable thanks to operators, operations you can insert between your Observable and your Subscriber and which transform the data in ways that are easier for you to handle. I only have one such example of this in the code above (transforming an OnTextChangeEvent into a String) but you get the idea.

Another benefit that should be immediately obvious to you even if you don't buy into the whole Rx paradigm shift yet is that thanks to Rx, we now have a universal language for observables and observers. I'm sure that right now, your Android code base contains a lot of such interfaces, all with subtly different method names and definitions and all needing some adapaters to be inserted before they can talk to each other. If ever you felt the need to write an interface with a method called "onSomethingHappened()", Rx will be an immediate improvement.

Operators

I have barely touched upon operators and this topic in itself is worthy of an entire book but I'd like to spend a few minutes to give a quick example of the power of operators.

Going back to our activity, remember that as soon as the user types more than three characters, we send a query to the network for each character typed. This is a bit wasteful: a lot of phone users are very fast typists and if they type letters in quick succession, we could be sparing our server some extra work. For example, how about we define that we only call the server when the user stopped typing?

How do we define "stopped typing"? Let's say that we'll decide that the user stopped typing if two keypresses are separated by more than 500ms. This way, a quick typing of "cedric" will result in just one server call instead of four without this function. How do we go about implementing this?

Again, the traditional approach would mean that each time our text change listener is invoked, we compare the current time with the timestamp of the last character typed and if it exceeds a certain value, we trigger the event.

As it turns out, observables have an operator that does this for us called debounce(), so our code becomes:

WidgetObservable.text(editText)
    .doOnNext {(e: OnTextChangeEvent) ->
        addFriendButton.setEnabled(false)
        loading.setVisibility(View.INVISIBLE)
    }
    .map { e: OnTextChangeEvent -> e.text().toString() }
    .filter { s: String -> s.length() >= 3 }
    .debounce(500, TimeUnit.MILLISECONDS)
    .subscribe { s: String -> mNameObservable.onNext(s) }

I know what you're thinking: "You just picked a problem that could be solved by an operator that already exists". Well, kind of, but that's not my point. First of all, this is not a made up problem and I'm sure a lot of developers who write user interface code will agree that this is pretty common.

However, my point is more general than this: the debounce() operator has nothing to do with Android. It is defined on Observable, which is the base library we are using. It's an operator that's generally useful to have on any source that emits events. These events might be graphical in nature (as is the case here) or of any other kind, such as a stream of network requests, coordinates of a mouse cursor or capturing data from a geolocation sensor. debounce() represents the general need for getting rid of redundancies in streams.

Not only do we get to reuse an existing implementation without having to rewrite it ourselves, we preserve the locality of our implementation (with the traditional approach, you would probably have polluted your class with a couple of fields) and we maintain the composition abilities of our observable computations. For example, do you need to make sure that the user is not adding themselves before calling the server? Easy:

WidgetObservable.text(editText)
    // ...
    .filter { s: String -> s.length() >= 3 }
    .filter { s: String -> s != myName }

Wrapping up

At this point, you should probably take a look at the full source so you can step back and see how all these pieces fit together. It's obvious to me that the view of decomposing your problem in terms of observables that emit values that subscribers observe is extremely powerful and leads to cleaner, more self contained and composable code. The non-Rx version of this class feels incredibly messy to me (a lot more fields holding state, methods added just to satisfy slightly incompatible listener interfaces and a total lack of composability).

Having said that, our work here is not over:

  • The threading model is all wrong. I intentionally omitted any thread consideration in this article in order to stay on topic but the code as it is right now is extremely suboptimal. It works but you shouldn't ship it in its current form. In the next installment, I will show how Rx makes it trivial to get Android's multithreaded model right.
  • There is a lot of UI code peppered through the business logic. It's messy, it obfuscates how our UI works and it's hard to maintain. We'll have to fix that as well.

Stay tuned!

Update: Discussion on reddit.

“New Comments”: A Chrome extension for reddit and Hacker News



I recently became tired of how awkward following discussions on Hacker News and reddit is so I decided to write a Chrome extension to address the problem. The result is “New Comments”.

This extension will trigger only on Hacker News and reddit. When you read a comment thread on either of these sites, the extension will compare the current time with the last time you refreshed it, locate all the new comments and highlight them. If you enabled Chrome sync, the extension will work across all your computers so that you can start reading a discussion on your laptop and keep reading it later on your desktop with only the correct new comments highlighted.

Some of the lessons I learned in the process:

  • Writing a Chrome extension is ridiculously easy and the debugger is top notch.
  • Chrome’s storage API makes it trivial to build on top of Chrome sync.
  • Javascript is productive but still frustrating because of its lack of types. Even when the code was just a handful of functions, I was already beginning to hit bugs coming from the absence of the type system. I used the debugger as a substitute for types way too often.
  • Following this, I realized that my inclination to refactor and polish the code was considerably lessened. The code is pretty ugly as it is, with string literals splattered a bit everywhere and a questionable module structure, but once it was working, I didn’t feel the urge to make it perfect that I usually feel with a statically typed language and a powerful IDE under my fingers.

If you read Hacker News or Reddit and you’d like to optimize your time spent on these sites, try New Comments and let me know what you think!

A Rubik’s cube implementation in Three.js



In 2003, I took the time to put together a page that explains how to solve the Rubik’s cube with a set of formulas that are easy to memorize. The idea was not necessarily to solve the cube quickly (it takes about 50-60 seconds to solve the cube with this approach) but to make it easy for anyone to beat the cube with little effort, as opposed to the hundreds of formulas that speed cubists have to memorize to remain competitive.

Back then, I used a Java applet that represents a cube with formulas and then playing these formulas to explain to the reader how exactly they work. As everybody knows, Java applets have fallen out of favor even more today than they already were ten years ago, so I’ve been wanting to update my page with more modern technologies for a while, especially if these technologies don’t show a scary warning to everyone who reaches my web site.

I finally took the time to update my page and I reimplemented the entire cube animation in Javascript with Three.js. Here is how it looks like today.

While it’s easy to find rapidly implemented Rubik’s cubes in Three.js, I couldn’t find anything that came remotely close to what I needed, namely, being able to configure a cube directly from the HTML page along with the formula, and playing this formula at the click of a button. Three.js turned out to be a great match for this, with the perfect amount of abstraction and power. And with Three.js came a few free bonus tools, such as being able to move the cube around and also effortlessly zooming in and out. Of course, it’s equally trivial to modify the size of the cube, the position of the camera, the field of view, and just as easy to add more fancy stuff such as lighting, shadows and fancy materials.

The implementation is open source but I want to write some proper documentation before publishing it.

Overall, the experience was fairly pleasant. My relationship with Javascript is stormy at times (I’m planning to rewrite this in Dart at some point to compare) but in the end, using both IDEA and Eclipse to write the code (switching between both to compare) and with the Chrome debugger in a separate window, the productivity level is pretty high.

Implementing the cube itself was the most interesting part: there are so many ways you can model a Rubik’s cube that such a problem is a software designer’s dream. I must have had three different iterations of the data model before I settled on the version you see now (and I’m already thinking of ways I could improve it).

Three.js has come a long way since I gave it a try two years ago. The web is still filled with incorrect information referencing an old API that has since then changed, but it’s very intuitive and, most importantly, it allowed me to completely avoid having to deal with the WebGL madness. I don’t know if it’s my brain that’s just not wired for this, but I have tried to read countless OpenGL tutorials over the past years and every time, I give up after an hour, my eyes glazing over the intricate, effect-littered, abstraction empty details of OpenGL. The API is probably too low level for someone like me with just a passing interest for gory graphical details.

My knowledge of computer graphics and animation is abysmal overall, so this was a great opportunity to move myself out of my comfort zone and force myself to confront problems that I usually never encounter, such as finding tricks to counter floating point rounding errors and revising matrix multiplications and other miscellaneous linear algebra and 3D geometry concepts such as quaternions and gimbal locks.

Swift, Apple’s new language

Apple just announced a new language called Swift. I took a look at the language manual, here is a quick overview:

  • Statically typed with type inference.
  • Generics.
  • Closures.
  • No exceptions.
  • Extension methods.
  • Properties (syntax similar to C#), including lazy properties with the "@lazy" annotation.
  • Functions, methods and type (static) methods.
  • Support for observers (with "willSet" and "didSet"). Interesting to see the observer pattern baked in a language although I’m more partial to event buses for this kind of thing.
  • Enums.
  • Classes and structures (structures have restrictions regarding inheritance and other things).
  • For and while loops (statements, not expressions).
  • "mutating" keyword.
  • Named parameters.
  • Deinitializers (finalizers).
  • Protocols (interfaces).
  • Optional chaining with "a?.b?.c" and forced dereference with "!."“.
  • Convenient “assign and test”: "if let person = findPerson() ...".
  • Type casting with "is", down casting with "as?" (combines nicely with the "let" syntax. Ceylon does it right too).

Very interesting overall, and a clear step up from Objective C. From the feature set, I would say the language that Swift has the most overlap with is Kotlin, which is great news for Apple developers.

Update: discussion on reddit.

Coding challenge: partial results semantics

Consider the simple following signature:

  List<Person> searchPeople(String query);

This method takes a search string (e.g. “Bill”) and returns a list of Person that match this search string. This includes people with “Bill” as their first name, or as their last name, or maybe even using nicknames (someone whose name is “William” would match).

However, you have millions of people in your database, which means that this function call can potentially return tens of thousands of people, and it can also be quite time consuming. But your caller cannot wait forever and they want to cap the amount of time you spend doing the search, e.g. five seconds.

The function itself doesn’t know about this limit, it just does as much as it can and then it gets interrupted by its caller after the time has run out. You can imagine that the caller invokes this function in a separate thread and then calls get on the Future with a time out of five seconds.

The nice thing about the signature above is that it’s referentially transparent, which offers a lot of nice properties. However, it’s also binary: either it returns everything that matches the search or it gets interrupted before it can finish and the caller gets zero results.

The challenge is to write this function so that when it gets interrupted by the time out, it still returns whatever it has found so far.

The solution is trivial using mutable structures so bonus points if you can implement this solution with immutable data. Any language welcome, and I suggest you use pastebin or a similar service to share your code, since the comment system is not very good at formatting code.

More about language popularity

Hot on the tail of my previous post about language popularity, the latest numbers from the TIOBE are out.

The top five languages are C, Java, Objective-C, C++ and Visual Basic. Every other language beyond that has less than 4% mind share. The next JVM languages are Scala (#35) and Groovy (#48). Clojure didn’t make it in the top 50.

The pitfalls of Test-Driven Development

A few days ago, David Heinemeier Hansson posted a very negative article on Test-Driven Development (TDD) which generated quite a bit of noise. This prompted Kent Beck to respond with a Facebook post which I found fairly weak because it failed to address most of the points that David made in his blog post.

I have never been convinced by TDD myself and I have expressed my opinions on the subject repeatedly in the past (here and here for example) so I can’t say I’m unhappy to see this false idol finally being questioned seriously.

I actually started voicing my opinion on the subject in my book in 2007, so I thought I’d reproduce the text from this book here for context (with a few changes).

The Pitfalls of Test-Driven Development

I basically have two objections to Test-Driven Development (TDD).

  1. It promotes microdesign over macrodesign.
  2. It’s hard to apply in practice.

Let’s go over these points one by one.

TDD Promotes Microdesign over Macrodesign

Imagine that you ask a famous builder and architect to construct a sky scraper. After a month, that person comes back to you and says

“The first floor is done. It looks gorgeous; all the apartments are in perfect, livable condition. The bathrooms have marble floors and beautiful mirrors, the hallways are carpeted and decorated with the best art.”

“However,” the builder adds, “I just realized that the walls I built won’t be able to support a second floor, so I need to take everything down and rebuild with stronger walls. Once I’m done, I guarantee that the first two floors will look great.”

This is what some premises of Test-Driven Development encourage, especially aggravated by the mantra “Do the simplest thing that could possibly work,” which I often hear from Extreme Programming proponents. It’s a nice thought but one that tends to lead to very myopic designs and, worst of all, to a lot of churn as you constantly revisit and refactor the choices you made initially so they can encompass the next milestone that you purposefully ignored because you were too busy applying another widespread principle known as “You aren’t going to need it” (YAGNI).

Focusing exclusively on Test-Driven Development tends to make programmers disregard the practice of large or medium scale design, just because it no is longer “the simplest thing that could possibly work”. Sometimes it does pay off to start including provisions in your code for future work and extensions, such as empty or lightweight classes, listeners, hooks, or factories, even though at the moment you are, for example, using only one implementation of a certain interface.

Another factor to take into consideration is whether the code you are writing is for a closed application (a client or a Web application) or a library (to be used by developers or included in a framework). Obviously, developers of the latter type of software have a much higher incentive to empower their users as much as possible, or their library will probably never gain any acceptance because it doesn’t give users enough extensibility. Test-Driven Development cripples library development because its principles are at odds with the very concept of designing libraries: think of things that users are going to need.

Software is a very iterative process, and throwing away entire portions of code is not only common but encouraged. When I start working on an idea from scratch, I fully expect to throw out and completely rewrite the first if not the first two versions of my code. With that in mind, why bother writing tests for this temporary code? I much prefer writing the code without any tests while my understanding of the problem evolves and matures, and only when I reach what I consider the first decent implementation of the idea is it time to write tests.

At any rate, test-driven developers and pragmatist testers are trying to achieve the same goal: write the best tests possible. Ideally, whenever you write tests, you want to make sure that these tests will remain valid no matter how the code underneath changes. Identifying such tests is difficult, though, and the ability to do so probably comes only with experience, so
consider this a warning against testing silver bullets.

Yes, Test-Driven Development can lead to more robust software, but it can also lead to needless churn and a tendency to over-refactor that can negatively impact your software, your design, and your deadlines.

TDD Is Hard to Apply

Test-Driven Development reading material that I have seen over the years tends to focus on very simple problems:

  • A scorecard for bowling
  • A simple container (Stack or List)
  • A Money class
  • A templating system

TDD works wonders on these examples, and the articles describing this practice usually do a good job of showing why and how.

What these articles don’t do, though, is help programmers dealing with very complex code bases perform Test-Driven Development. In the real world, programmers deal with code bases comprised of millions of lines of code. They also have to work with source code that not only was never
designed to be tested in the first place but also interacts with legacy systems (often not written in Java), user interfaces, graphics, or code that outputs on all kinds of hardware devices, processes running under very stringent real time, memory, network or performance constraints, faulty hardware, and so on.

Notice that none of the examples from the TDD reading materials fall in any of this category, and because I have yet to see a concrete illustration of how to use Test-Driven Development to test a back-end system interacting with a 20-year-old mainframe validating credit card transactions, I certainly share the perplexity of developers who like the idea of Test-Driven
Development but can’t find any reasonable way to apply it to their day jobs.

TestNG itself is a very good candidate for Test-Driven Development: It doesn’t have any graphics, it provides a rich programmatic API that makes it easy to probe in various ways, and its output is highly deterministic and very easy to query. On top of that, it’s an open source project that is not subject to any deadlines except for the whims of its developers.

Despite all these qualities, I estimate that less than 5% of the tests validating TestNG have been written in a TDD fashion for the simple reason than code written with TDD was not necessarily of higher quality than if it had been delivered “tests last.” It was also not clear at all that code produced with TDD ended up being better designed.

No matter what TDD advocates keep saying, code produced this way is not intrinsically better than traditionally tested code. And looking back, it actually was a little harder to produce, if only because of the friction created by dealing with code that didn’t compile and tests that didn’t pass for quite a while.

Extracting the Good from Test-Driven Development

The goal of any testing practice is to produce tests. Even though I am firmly convinced that code produced with TDD is not necessarily better than code produced the traditional way, it is still much better than code produced without any tests. And this is the number one lesson I’d like everybody to keep in mind: how you create your tests is much less important than writing tests in the first place.

Another good quality of Test-Driven Development is that it forces you to think of the exit criteria that your code has to meet before you even start coding. I certainly applaud this focus on concrete results, and I encourage any professional developer to do the same. I simply argue that there are other ways to phrase these criteria than writing tests first, and sometimes even a simple text file with a list of goals is a very decent way to get started. Just make sure that, by the time you are done with an initial version, you have written tests for every single item on your list.

Don’t test first, test smart.


Update: Discussion on reddit

Language popularity on GitHub

RedMonk just published their latest survey of Github’s most popular languages, and given Github’s continuous growth in popularity, they are worth a look.

Here are the results at a glance:

  • Javascript is seeing a consistent and serious growth.
  • Ruby is in sharp decline.
  • Python is showing a decline as well, although not as severe as Ruby.
  • Java is showing some growth, and it’s also the only JVM language in the top 12 listed by Red Monk.

I’m going to go out on a limb and predict that Python is being replaced by Go. I don’t have a lot of information to back up this prediction except that most of the positive articles I read about Go are written by Python developers, and a lot of them say that they are now actively migrating their code base from Python to Go. I don’t see as much enthusiasm for Go from developers using statically typed languages, probably because of Go’s antiquated type system (which is still a big step up from Python, obviously).

It’s interesting to see Java continue to grow twenty years after its introduction. I think this constant growth is fueled by the language’s remarkable versatility and its ability to adapt to new technologies but also driven by a series of constant popularity boosts such as Android five years ago and Java 8 this year.

I’m surprised not to see Groovy in this top 12 of languages, since it’s usually acknowledged as the second most popular language on the JVM and I expected its popularity grow thanks to Gradle, but this doesn’t seem to be enough to crack the top 12 on Red Monk.

Update: Discussion on reddit

A bit I can’t unsee

This is the binary definition of ET’s sprite, in Atari’s infamous game:


ETWalkSprite_A0
.byte $FE ; |XXXXXXX.|
.byte $FF ; |XXXXXXXX|
.byte $C3 ; |XX....XX|
.byte $0F ; |....XXXX|
.byte $FF ; |XXXXXXXX|
.byte $3F ; |..XXXXXX|
.byte $2B ; |..X.X.XX|
.byte $E7 ; |XXX..XXX|
.byte $00 ; |........|

I am actually less disturbed by the 6502 listing than by this extra bit between ET’s legs (which you can see on the screen shot above).

Coding challenge: fast width/height of an image

I am trying to find out the width and height of an image (a URL) transferring as few bytes as possible. This coding challenge has two separate parts:

  • Finding the cheapest way to retrieve width and height.
  • Verifying that the solution is indeed cheap.

The first part is not that interesting since it’s a fairly well documented problem. A bit too documented, actually, since I found several solutions:

This last solution looks pretty efficient from a network perspective but I’m worried it might leave out a few corner cases in image handling. The first two solutions are probably battle tested and very robust but I have no idea how effective they are from a network standpoint (their Javadoc doesn’t describe the specifics of how they operate).

So… Do you have a better solution? And whether you do or don’t, how would you assess how many bytes these implementations transfer?