Is checking "http_status / 100 != 2" better than "http_status != 200"

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


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.


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!
}

Tags:

Java