Thursday, November 21, 2013

Story of a ghetto coder

Believe or not, I was called a ghetto coder when I was doing testing automation. The story was like this, a software feature was implemented, but missed an important feature: "Save As". So users of the system can't save his/her configurations. I wrote a tool that extracts relevant part of user configuration on that feature from the system configuration (a big xml blob) and save it to a file and be able restore the configuration from a file. This workaround served the purpose of "Save As". I was happy and expected some compliments, but was surprised that one "compliment" was "ghetto coder". Why? I did the extraction(from a big xml string) by regular expression :-( Later on, I changed the tool to use tdom package - the official and better way on extraction from xml string, but the nick name remained. I was actually happy at the outcome since many colleagues got to know this nickname. Whenever they needed some tools urgently, they came to this "ghetto coder" and they usually got something working shortly after. I guess the word "ghetto" has turned into "quick and dirty" and it can be helpful in some cases.

It reminded me of the story when I saw someone asked a question on performance testing: Given a server response like the following,

{"id":{"idUri":["/id/123123"]}}

how to extract the field "/id/123123"? The answer was given using regular expression:

"idUri": \[ "([^"]+?)" \]

While the regular expression works for this particular string, I was worried that if the spacing changes a little bit (like some white space was removed or added, a new line was inserted after "["), this regular expression may fail.

a = fromJson(str);
//now variable a.id.idUri[0] contains the desired field

Here the structure of the variable a.id.idUri[0] follows the hierarchy of the json message, so it's fairly easy to understand. Note that in particular, the array ("idUri" in this case) is 0 based, so idUri[0] means the first element.
This will work no matter how the spacing changes. Should there be a second element in the "idUri" array, it can extract that element too (just use a.id.idUri[1] instead) . On top of all these, this is much easier for someone with basic programming skills than the complex regular expression.

My experience as "ghetto" coder taught me that it's ok to write "ghetto" code, but you or the users need to be aware of the possible conditions that can cause it to break. Also, if there is an easy way to do the task in a better way (like using tdom package to extract part of xml string), jump on it.