My life be like

Side effects

“A function should not have behaviour that is not expected.” Published at: 2019-02-10

When developing you learn new things every day. Sometimes new things you didn’t know and sometimes things you already knew are confirmed. When I first started developing I learned things but never experienced them. One of the rules is that functions should not have side effects. That means that a function modifies the state of the computer, like changing a variable. I found a function that does precisely that. When a user makes a request to the REST API, the headers are stored in a Request object. We can use this object to use the request to do something with it. I wanted to test is the request has a certain header. But the test always failed.

public function hasHeader ($name) {
    return array_key_exists(mb_strtolower($name), $this->headers);

This is the method. The method checks if Header exists in the list of headers. Heres an example when testing this method.

$headers: [
    "Accept" : "application/json"
$request: new Request($headers);
$request->hasHeader("Accept"); // Always returns false.

It always returns false, because when calling the method the parameter is casted to a lower string to compare. So the header is capitalized (as done in RFC2616) and the parameter to check if the header exists is casted to lower case. This is unexpected behaviour and can be quite cumbersome.

Lesson learned: Don’t change things that aren’t expected to change.

Oscar te Giffel

Oscar te Giffel. I wan't to learn so many things. This is just my journey through life.