Friday, August 28, 2015

Quicker and Easier headers with HTTParty

You may remember last month I showed how to retrieve just the headers in an HTTP request using the HTTParty ruby gem.

At that time, there were a couple of extra options that needed to specified in the case of redirects, otherwise on each subsequent redirect, the HEAD request would be converted to a normal GET request. This wasn’t ideal because the reason I was doing HEAD requests in the first place was to save the time it would take to retrieve the entire page and instead just find out whether the request was successful. It also didn’t make much common sense.

So I changed the gem. It now follows redirects and maintains the HEAD request across all redirects.

This is one of the reasons I really enjoy working in code. There’s this great tool that works extremely well in most cases, but there’s something slightly off about one small part of it. Rather than making a support request to some big conglomeration that may or may not read it and may or may not fix the issue, I can just jump in, make the change, and hopefully help improve the functionality for myself and, in the process, for countless others.

Wednesday, August 26, 2015

Hidden pitfalls of comparing strings in Java

I’ve been learning some Java to get into Android coding. It is certainly more verbose compared to Ruby. As a simple example (which will lead me into the topic at hand), let’s say I have a variable called word with the string “widget” stored. If I want just the first letter of the word:

# Ruby
word[0]

// Java
word.substring(0,1);

What’s more, the Ruby method above returns a normal String object that can be acted on like any other string. So, if in Ruby I wanted to check if the first letter in the word was “w”:

# Ruby
word[0] == "w"

Based on that, I figured I could do something similar in Java:

// Java
word.substring(0,1) == "w";

Fail! And it’s the worst kind of fail - it doesn’t even give an error! It just returns false, even though I know that word.substring(0,1) will return “w”.
When I tried a few combinations of things in javarepl, I got some interesting results:

String letter = word.substring(0,1);
letter == "w";
// ERROR: illegal start of expression
// = "w";
// ^

and

"w" == "w"
// java.lang.Boolean res9 = true

but

word.substring(0,1) == "w";
// java.lang.Boolean res10 = false

Really strange. My guess is that in the first example, it’s trying to assign “w” even though I’m attempting to use the equality operator. But if that’s true, I have no idea why it’s doing what it’s doing in the other two.

Just for posterity, the way to get the third example to return true like it should is to use the equals method:

word.substring(0,1).equals("w");
// java.lang.Boolean res11 = true