31

When talking about HTTPUrlConnection on his blog Tim Bray gives us the following snippet for checking the HTTP status code

// better check it first
if (http_status / 100 != 2) {
  // redirects, server errors, lions and tigers and bears! Oh my!
}

Is http_status / 100 != 2 better or faster than http_status != 200

1
  • 2
    As of @Madhu Bhat answer This is the right way to check whether it is 2xx or not if (!HttpStatus.valueOf(http_status).is2xxSuccessful()) { // redirects, server errors, lions and tigers and bears! Oh my! } Sep 17, 2019 at 10:55

7 Answers 7

29

The reason that's done is because status codes are integers, so this expression will be an integer division.

The integer division means that all successful HTTP status codes (i.e., those from 200-299) will make the expression false, not just 200.

Not to nitpick on Tim Bray, but if I was writing this myself and wanted to convey my intent clearly, then for readability purposes I'd probably want to see something more like !statusCode.isSuccessful. If you didn't know that HTTP 2xx meant successful status codes, it wouldn't be obvious what the intent of the integer division was.

Of course, integer division is probably more performant than making a bunch of hypothetical StatusCode objects and then doing isSuccessful method dispatch on them. And performance is probably a key goal for a network library class.


Is http_status / 100 != 2 better or faster than http_status != 200?

It won't be faster (two operations vs. one), but whether it's "better" is an apples-to-oranges comparison since those two operations have different behavior.

8
  • +1 for the explanation of why you'd want to do this, but the QUESTION really should be, is the division and equals check better/faster than a check of a RANGE of values, because that's what the division represents.
    – dldnh
    Mar 18, 2012 at 16:14
  • And this trick is nice and quick if you are just checking if the operation is successful but don't care about the granular definition of success the server is reporting. You'll likely know whether you need finer grained information from the response.
    – gorjusborg
    Mar 18, 2012 at 16:15
  • Doesn't this need to be wrapped in something like a parseInt()? 250 / 100 === 2.51.. so the expression, httpCode / 100 != 2 would still resolve to TRUE, would it not?
    – RavenHursT
    Feb 4, 2016 at 22:00
  • 1
    @RavenHursT No. Integer division does not produce floating point values. 5/2 = 2. Feb 5, 2016 at 2:10
  • 1
    @RavenHursT This question and the linked post of Tim Bray's are both about Java, not JavaScript. What you're seeing in the Chrome console and other V8 implementations is JavaScript (an implementation of ECMAScript, and thus a different language entirely from Java). In Java, 5/2 performs integer division. Feb 5, 2016 at 19:35
28

I've seen many codes with hard coded validation, and had problems with this aproach frequently.

When I do refactoring on this kind of code, the aproach I use the most is implementing the verification with a class from javax-ws: javax.ws.rs.core.Response.Status.Family

something like this:

if(Response.Status.Family.familyOf(responseCode).equals(Response.Status.Family.SUCCESSFUL)){
    //do your thing
}

You can also check for other kinds of status:

  • INFORMATIONAL - 1xx
  • SUCCESSFUL - 2xx
  • REDIRECTION - 3xx
  • CLIENT_ERROR - 4xx
  • SERVER_ERROR - 5xx

JavaDoc: Response.Status.Family

1
  • 1
    I don't have the familyOf method available (probably different version of javax.ws.rs.core). You can also get the Family by doing Response.Status.fromStatusCode(responseCode).getFamily()! Apr 11, 2018 at 8:50
26

Spring's HttpStatus provides methods like is2xxSuccessful(), is4xxClientError() etc which can be used to check if the HttpStatus belongs to any particular family of HTTP status codes.

So if you want to handle the condition if the status code is NOT belonging to 2xx, you can do the below:

if (!HttpStatus.valueOf(http_status).is2xxSuccessful()) {
   // redirects, server errors, lions and tigers and bears! Oh my!
}
13

http_status / 100 != 2 is not the same as http_status != 200. It's essentially equivalent to (http_status < 200 || http_status > 299) (remember that anything in that range constitutes "success").

That said, doing a divide is horrible, and completely obtuse. I would always use the explicit comparison, because then the intent is clear.

1
  • Damn I concentrated so hard on the " / 100 != 2" I totally forgot about codes through 201 - 299
    – Ravi Vyas
    Mar 18, 2012 at 16:42
8

One pro in favor of Tim Bray's division method to detect non-200 level messages is that it is easier to unit test.

This method below would need to be tested three different times; 2xx, 1xx, and > 299.

(http_status < 200 || http_status > 299)

This method requires only two.

http_status / 100 != 2

This is not to say that it is always better to use the division method versus the compare, but it is one point worth making. In a project I am working on, where the speed diff between these two methods is not an issue, I prefer Tim Bray's division method because it leads to one less test case to have to test. We have strict guidelines for code coverage.

1
  • 1
    Good point, but as painful as it is, first method is more clear on intent and arguable a good choice too. Apr 26, 2016 at 19:51
4

Assuming http_status is an integer (so the division returns an integer), it's not better or faster, but different.

It will allow any 2nn status code to trigger that condition. A 2nn status code...

...indicates the action requested by the client was received, understood, accepted and processed successfully.

Source.

2

Please note that RFC 4918 introduced the status code 207 Multi Status. This was intended for WebDAV but some developers may find it handy when the request relates to several resources (for instance: deleting a bunch of orders).

While starting with the number 2, a 207 response is expected to provide information about the status of the individual resources (such as orders). It is possible that one of those statuses would be an error.

I know this is far fetched, in doubt better check the API you're consuming.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.