Clean Code – Reusing HTTP Codes for Encoding

clean codehttp

As we know HTTP codes are used in HTTP response. Usually with this code we can have an idea about what happened. For example if I make a get request and I obtain a 404 I can figure out that the resource that I requested doesn't exist on the server side.

Suppose that I want to encode the status of an object in the DB. For example let's say that if the object exist but some data are missing (a specific field for example) I want to save it in my DB but express the status of the object with a column. This need to be an integer (suppose it is a constraint). I would go for 206 (partial content in HTTP).

From a code point of view suppose we have an enum to express the various possible status as this one:

public enum ValidationStatus {

    OK(HttpStatus.OK.value()),
    PARTIAL(HttpStatus.PARTIAL_CONTENT.value()),
    ...

    private final Integer code;
    ...

When someone reads the code, it seems that HTTP is involved in some way. But in this case it’s not. I'm reusing the HTTP status to represent something else.

I saw that in a project but I'm not sure about if this is a good practise. It’s like mixing things for me. I'm using something created for HTTP to represent something else.

Do you think that it is acceptable?

EDIT: to be more precise my was just an example of reusing HTTP code in other context. Actually in the DB is stored the string value (in this case PARTIAL) but in this microservices application, the services communicate with messages and in these messages you find the integer. When for example an object is in the status PARTIAL a notification is send to another service as if it is a sort of error. This question arose when I was running some tests, and in the log I so this: "ERROR 206 PARTIAL". I saw this and the HTTP 206 status came into my mind. After that I discovered the use of this code in the application and so the enum class. My initial confusion brought me to ask this question. The I discovered that HTTP was not involved at all.

Best Answer

I would advise against it. The most likely result is that you will create confusion with future developers/maintainers.

  • You are using the codes outside of the context of HTTP, so you will probably get questions about what happened to the status codes with values 0 to 199. In the database, the fact that the codes begin at 200 does not have any inherent meaning.
  • As mentioned in another answer, the HTTP status codes may not be specific enough, so you would have to invent new values that you have to give a meaning yourself (and which may conflict with future HTTP status codes).

After you have had to invent your first application-specific status code, any advantage you may have had previously that the values were 'well known' and didn't need to be documented by you is now gone as well and there is no reason left not to do the conventional thing and count your status values from 1 (or 0).