Saturday, July 04, 2009

No way to get in the zone? Here's the cure: idea refactoring

An assumption: software programming and engineering is hard. Abstracting the world and put it in a computer is a complex task and the knowledge of the concerns of our job distinguish us from the script kiddies. The zone, or flow is the particular mental state in which a person is fully immersed in his activity, and reports great advance in his work, enjoying it. The flow is tipically killed by interruptions of the work and is difficult to reach before a quarter or even an half hour of working.
This post is inspired by Getting Things Done, the book from David Allen that teach techniques to enhance your productivity and your focus.

A simple collecting process
In an agile world, monolithic analisys of requirements and design has not place, but simply writing down in detail the actions you are going to take for a task accomplishment is a technique that has only advantages compared to the small time needed:
- it forces to search a way to do the task, and once a ten steps to ... is in place you will find easier to find the energy to do all those things. This is far the most important technical advantage: when you jump in coding you won't find a list with integrating a dojo grid, but writing a view helper for the datastore, writing a view helper for the grid itself, make sure it is tested on this particular use case, and so on. We'll talk later on how this affect the time you will spend to reach the zone.
- naming things gives man power over them: as philosophers says, finding early an ubiquitous name for the components of your software will help you to build a mental model of it.
- you can write details whenever you want, because little energy is required. The only constraint is to have mental focus on the problems you are watching, a thing that once you go further and further in a project is very likely to be automatic.
- you can find out if a task is impossible to do or it has to be postponed: if you can't find a step-by-step process to accomplish it, probably the reason is it will be impossible with this specific requirements, or it will be a great time-sucker while you can find an equivalent feature that can substitute it and do less.
- you can cancel out subtasks when you have completed them: when you're talking about high level goals there's not even a definition of done, while decomposing them gives you a medium sized list to write + on when you have write some tests or implemented a specific class.
- in general, jump right to the coding phase is not a good idea. TDD can help to stay in the zone while developing a specific class/component/unit/procedure, but firstly you have to define what the classes are. Obsiously there's no need to write a Uml-compliant diagram or a [insert buzzword here] model, but the power of plain text can help.

Find a way becomes easy if you refactor ideas
During the day I set up my todo list and write in plain text files every idea that comes to my mind, being sure that it will not be lost in the recess of my memory. I simply accept that I cannot find a road that leads to my feature at the very moment when I write its name on my list.
In the evenings, when I have still ideas but I am too exhaust to do real work, I read feeds and develop my todo list, applying the process described above. After every task (features or enhancements to Ossigeno for instance) I write an indented sublist that decompose the task in the steps needed. Then I repeat the process with the subtasks which I find interesting at the moment, and on whom I have much inspiration.
What I end with is a list with various steps that are very low level; when I wake up in the morning, I can focus on the project very quickly. I find this written notes very useful to keep an eye on the whole situation and to always know the next action I have to take. Like doing TDD, starting by doing low level tasks that tells you all step by step is a powerful way to reach and stay in the zone. In TDD the steps are red/green/refactor, while here they are read/implement/enjoy (and maybe writing a blog post about it).

A live example
Last week, I was wondering how to protect the /scripts folder of Ossigeno, that contains the installation scripts and other admin features. Before I jump in developing an authentication system against a Kerberos server, I write down this task in the to-do list of Ossigeno.
Later, I refined the task and see that this could be simply done with a couple of .htaccess/.htpasswd files in the scripts/ directory: the idea was producing a generated couple of files basing on an installation form data (username and password). This requires the two files or the folder to be writable, and the generation of .htaccess is also needed because the authentication system of Apache needs an absolute path to the .htpasswd file, that depends on the specific deployment. Moreover, the htpasswd file contain a crypted password and I also had to find its format.
With further refinement, it became clearer that some subtasks were not so hard but a bit longer to implement to be justified by the value they provide, and I deleted the generation of htpasswd and form part; please note, before to reallly write it. This is the most powerful refactoring, because it's done even before writing the code.
The final solution was to write on installation a generated scripts/.htaccess file to point to the realpath() of the htpasswd file, basing on a template. The user is free to substitute the included htpasswd file containing default password with what he wants. The coding was done and tested in five minutes, once I know how and what to code for.
And that's the point of idea refactoring: find the simplest way to develop a feature by leaving your subsconscious brain working on the problem during the day.

10 Doctrine gotchas

Here is a list of tips for Doctrine usage in php projects, ranging from hydration to magic method. They are valid for the 1.x versions.
I am currently working on generation of Zend_Form instances based on Doctrine objects, that use model metadata to create form elements of the right type. Doctrine is very powerful, but while developing Otk_Form_Doctrine, I had some gotchas that I'd like to share with other php developers that use this orm.
  1. findAll() and findOne*() does not hydrate the object. If you obtain a collection or a record with one of these methods, a subsequent access to a relation would raise a new query to the database. Hydration should be your repositories concern, and you have to decide what relation hydrate by default.
  2. you can generate table classes, with proper options set in Doctrine facade calls. "generateTableClasses" is the option needed, see the documentation for examples.
  3. fixture keys are unique throughout the whole set of files imported. This means that if you have a bunch of yaml files where you write fixtures, you have to make sure that the keys of the various records are all different, so don't use 1, 2, ... as keys, but meaningful names instead.
  4. unlink() is not permanent until saved. From version 1.1 of Doctrine, until you call save() on a record, unlinked relationship would not be reflected to the database. A more consistent behaviour than the previous 1.0 version one, where unlink() will automatically save changes when called. For a deep model introspection, it is better to have a single point of saving as we have now.
  5. Doctrine validation is turned off by default, so every save() might not saving all the data, resulting in truncated text fields...
  6. ...but if you turn it on, remember that a form value of "" on a integer field will result in a non valid record and save() will throw an exception().
  7. Doctrine many-to-many relations are bidirectional. So even if you don't define a side of a m-n relationship, it will be present in the record and will be listed by methods like toArray() when hydrated.
  8. The methods getRelations() and getColumns() of Doctrine_Table can give you a lot of introspection of the model from the script point of view. In my case, I was able to generate form elements and subforms according to the business object structure, for instance a dojo DateTextBox with a sexy calendar to represent a timestamp model column.
  9. __toString() is very useful in a Doctrine_Record subclass, putting together the identity fields of the object to represent it for various purposes like dumping or putting it in a list.
  10. __call() is also very handy in a decorator for a Doctrine_Record or Doctrine_Table object, used for proxying to the underlying instance methods.

Hope this tips help you to follow the Doctrine... :)

3 gems that will open your mind

Some links to writings that once read will change a bit of your life for the better. Not developers-only.
I'm not keen on making long lists such as '100 posts that rocks', so here's a much smaller one. Only articles that caused an "ah-ah" moment to take place in me. The blogs where the posts come from are the ones that I would follow even without them having a feed.

To "new" or not to "new"
http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
Article on a practical concerns of Test-Driven Development. From Google.

The Joy of Solving Problems
http://www.stevepavlina.com/blog/2009/04/the-joy-of-solving-problems/
Not so software related, but it applies also in our field.

10 Benefits of Rising Early, and How to Do It
http://zenhabits.net/2007/05/10-benefits-of-rising-early-and-how-to-do-it/
That's how to find the time to do all those things...

Are dynamic languages evil?

Maybe unit tests for dynamic languages have to do what static language compilers already perform. But there are drawbacks like simple delegation...
The never ending religion war between static and dynamic languages has earned another debate with this post.
First, define what we are talking about: in static languages variables has a fixed type that has to be defined by the programmer when he writes the code. If we are talking about objects, you can only call methods on an object that belong to that particular class or interface. Example of these languages includes C (and its superset C++) and Java.
dynamic languages are the ones commonly used for scripting: Python and Php are the most widely spread in the open source world. In Php, $foo is a variable which type can change at any time. When you make an assignment in Python, the type of the variable matters in the subsequent executed code, but it is not checked at the compile time, primarily because there's no compiling in Php or Python (excluding the .pyc bytecode files and other stuff like Apc, whose compilation serve performance purpose and not proof of correctness).

Different architecture
Unit testing is a more radical proof of correctness of an application: it serves also to provide a specification for components, but the aspect of interest in this post is that the code is run. Static languages performs compile-time checking to catch bugs and errors even before the program loading.
However, static types checking is not enough to provide trust in code, so we have unit tests that loads the classes or procedures in question and feeds them canned data to see if they respond well.
In dynamic languages, we also have unit test (think of PHPUnit), but part of these tests are dedicated to ensure that the class does not explode. If there's a very dumb error, like passing wrong parameters to a method (string instead of array instead of object), this is discovered only when dispatching the real call, at runtime. With a single file in your editor, you can only run some syntax checking (php -l in our example).
This aspect is part of the dynamic languages architecture: the checking cannot be done a because the flow of the program will take a radical different road basing on the state of the script. In Java, a variable in a method is always the instance of the declared type; in Php it can be a string or integer or object depending on another string method value. Even the name of a method call can be a variable.

Dynamic point of view
On the other hand, these limitations on checking are the power of a dynamic language like Php, where for instance you can:
- call $object->$method()
- call $class::$method()
- code a decorator for a twenty methods interface with __call() and two lines of code.
- instance a domain model class basing on a parsed (and validated of course) string. This does not need reflection.
The decorator example is explanatory, because it's a rapid way to implement delegation using the __call() magic method. One __call() definition substitute the need to replicate all the methods signatures of the chosen class. Decorating a typical framework class of Doctrine or Zend Framework would otherwise require 100+ lines of code, making inheritance the choice even where composition would be better, to respect Lsp.
The introspection on the classes and methods provided by a dynamic language is not static checkable, but it's a very handful way to reduce verbosity and repeated code. Choose what is the right language for your job.

Why not using Sqlite for testing

Counter argument for testing in Sqlite: disadvantages of using it against a real database because of referential integrity.
Very Bad Things
Last week I blogged about using sqlite for testing and talk about the speed gain of this approach. But there'are also bad sides in using only sqlite as a mean to test your application.
Here's a simple list of problems I encountered during my experience in last months of using sqlite databases:
  • it's not the production database. It might seem a trivial point, but the other issues all comes out from this one. No matter what database abstraction layer you have, or what powerful Orm you are delegating, the cpu will not execute the same code that the production machine will. Period.
  • for instance, sqlite currently does not implement referential integrity. So I set up my forms and run integration tests and saw my domain objects gracefully saved in sqlite, but when I ran my browser on the staging machine exceptions were thrown by Doctrine being unable to save (or delete) objects due to referential integrity. This cause me a lot of headaches to reproduce the bugs in test environment, and if I haven't added additional infrastructure to test on a mysql database, I would never been able to replicate the behaviour and find a fix.
  • for the same reason, sqlite silently ignores every constraint in CREATE TABLE queries (or similar Ddl instructions, such as ALTER TABLE). This can cause very bad things happen, like a regeneration script that duplicates constraint of foreign keys that fails in production but not in test: the nightmare of a Tdder.
  • moreover, all your code that deletes or updates data flawlessly in test, can fail in production because breaks referential integrity.

So, what's the solution?
I have setup two phing targets (two phpunit bootstrap files will be the same, and are used respectively by my two phing targets) to launch the full test suite against the dummy sqlite database or against a full featured mysql database. This imply that after a bit of changes on classes that use the database, I run the slow test_mysql target and make sure that everything is correct. For what needs a database, the sqlite testing has become a smoke test.
The ideal setup would be a dedicated machine that implements continuos integration. Since it is dedicated it can waste time and cpu cycles to test all the day against every dbms I need to support. As the proverb says, databases are like women: can't live with them, can't live without.
Sqlite is a powerful tool that lets you do amazing things like testing database interaction from a netbook with no connection, but be careful: because, for your information, real database abstraction does not exist. :)

In-memory, but persistent, testing with Sqlite

When testing database interaction an in-memory database can be used with Sqlite. This solution is fast, but what if you want to see the state of database after termination or share it between processes, like multiple calls to phpunit?
A (maybe) long test suite
I have a test suite for Ossigeno (fully committed in the subversion repository) that prepares a dummy database and runs an hundred tests against it. It is started by a phing task that make some exec calls - one to the script that regenerates the database, and one or more to phpunit to run the test suite.
Having a dummy database is common: as is is always refreshed, the test failures depend only on the state of code. This free the suite from intermittent test, that pass and fail basing on what is store in the tables.
Using Doctrine as ORM, the models of Ossigeno are portable on all the dbms supported by the Doctrine abstraction layer or Pdo, so it's simple to prepare a fresh sqlite database (contained in a file), having thrown the previous version before regenerating. In production it is substituted by a real mysql database.

I don't want to wait
The test suite needs to be run fast: the point is that the more time it takes to complete a run, the more it's likely that after code changes the tests are executed, to not lost time waiting them to finish.
So the first step was already taken: moving from testing with an host with mysqld as infrastructure - remote or local - to a single db.sqlite file. This also makes the tests runnable on every machine with php-sqlite3 installed instead of mysql-server (for instance a netbook like my EeePc).
The next step is to eliminate the bottleneck of input/output on disk, slower than the memory. To take advantage of the features of sqlite, we can set the dsn of the connection to 'sqlite://:memory:' and the tables will be stored in ram instead that in a file.
However, this approach has some disadvantages:
  • the database will be thrown away when the Pdo connection is closed: we cannot take a look to it after the tests have been run;
  • when running a test in isolation, and not the full suite, the database must also be refreshed, since a more or less fresh instance does not exist anywhere.
  • since my regeneration script is executed in a separate process with exec, the database is deleted even before the first test starts.

The solution at Os level
Fortunately, I work on Unix machines. I use Ubuntu instances, but I guess Tiger/Leopard will do the same job.
Firstly, I configured sqlite to work on a file. Since it is a regular file (created when does not exists), it is persisted between connections and processes and my regeneration script can terminate gracefully and pass the token to tests; a single test can also be run in isolation on the existing db.sqlite file. All the advantages of the file approach are available.
But we want to store it in memory, so there's no i/o on disk and , so I execute:
$ sudo mount tmpfs -t tmpfs sqlite-folder/
to keep the database folder in ram. It is only wiped out on reboot.
This way, the full test suite has gone from taking 30-40 seconds to take less than 30 seconds, depending on the workload of the machine. On my EeePc I have configured the system /tmp folder to be mounted as tmpfs on startup also to reduce writing on the Ssd drive.
As a side note, accessed file in Linux are cached in ram, so probably if you repeatedly run the test suite using a file on disk you will get similar performance than mounting the directory in memory. On the other hand, if you run it for the first time in a while, it will work natively in ram, and you don't have to study the problem of how well your db file is cached in ram and how much cache misses will be encountered. Well, if :memory: dsn is available in sqlite, there's a significative difference from ram and cached disk sectors in ram.
Have a nice day with your Ram!

Using Apache Bench to monitorate performance

What about an application that feels 'faster' than yours? Or pages that seems to load slowly than others? We'll use ab command line tool to measure load times of your pages in scientific way. Example based on this Ossigeno installation.
Installation
Apache Bench is a command line tool, open source like Apache Httpd Server, that performs simultaneous and repetute requests to an url to simulate traffic and outputs a statistical analysis of performance.
On Ubuntu, it's available by:
$ sudo apt-get install apache2-utils
and then
$ ab ....
to execute Apache Bench.

Usage
Let's see it in action:
$ ab http://ossigeno.sourceforge.net/blog
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Licensed to The Apache Software Foundation, http://www.apache.org/

Benchmarking ossigeno.sourceforge.net (be patient).....done


Server Software: nginx/0.6.31
Server Hostname: ossigeno.sourceforge.net
Server Port: 80

Document Path: /blog
Document Length: 334 bytes

Concurrency Level: 1
Time taken for tests: 0.433 seconds
Complete requests: 1
Failed requests: 0
Write errors: 0
Non-2xx responses: 1
Total transferred: 632 bytes
HTML transferred: 334 bytes
Requests per second: 2.31 [#/sec] (mean)
Time per request: 432.576 [ms] (mean)
Time per request: 432.576 [ms] (mean, across all concurrent requests)
Transfer rate: 1.43 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 162 162 0.0 162 162
Processing: 271 271 0.0 271 271
Waiting: 271 271 0.0 271 271
Total: 433 433 0.0 433 433


That is a lot of info, and some noise is present. Ab has made one request to sourceforge.net and outputs time elapsed and other statistical info like mean and median. However, the most important parameter is Request per second, that represents how much different pages the httpd server can serve in 1s. Let's cut out unnecessary statistical data:

$ ab http://ossigeno.sourceforge.net/blog | grep Request
Requests per second: 3.02 [#/sec] (mean)

Ok, it seems that this server of sf.net can send out three pages every second. This is only one server: it has many and when we type ossigeno.sourceforge.net in our browser we are redirected through a load balancer to one of them.
Well, one request is not statistically significative: it can be noticeably faster than others because our request was sent in a particular idle instant. Or it can be slowed down because some cached elements were refreshed while serving our request. So let's do what a statistic will do: increase the sample size.

$ ab -n 100 http://ossigeno.sourceforge.net/blog | grep Request
Requests per second: 2.70 [#/sec] (mean)

Ab makes one hundred request in a row, and it calculates the mean of loading times. With this loading time, we see that this server can serve out 2 pages and a half every second. That's pretty fast.
What if simultaneous users request pages at the same time? A webserver is designed to have multiple process that works on different http requests. So, let's see if sourceforge.net is scalable:

$ ab -n 100 -c 5 http://ossigeno.sourceforge.net/blog | grep Request
Requests per second: 12.82 [#/sec] (mean)

Ab makes one hundred request, five at time, opening simultaneously five connection to sourceforge.net; we see that request per second is increased to ~13. What does it mean?
Let's put in this terms: if we request a page, it is sent to us in ~0.3s. If we request two pages at the same time, they are sent to us still in ~ 0.3s. So the server it's not a bottleneck at this level of concurrency, because it can handle 5 simultaneous request without slowing down them. If we increase concurrency level:

$ ab -n 100 -c 20 http://ossigeno.sourceforge.net/blog | grep Time
Time taken for tests: 2.082 seconds
Time per request: 416.397 [ms] (mean)
Time per request: 20.820 [ms] (mean, across all concurrent requests)
Connection Times (ms)

the time for serving one page increases to only 0.4s, that is a kick-ass performance.

Conclusion
Profiling is the essence of optimization: you have to see where is the bottleneck to improve your application.
Apache Bench is a useful tool as it monitor loading times of webpages, going beyond human sensations of "speed" and provides statistics calculated on a sample of request that you can choose. You can activate and disactivate some modules of server, like mod_deflate for Apache or apc at Php level or Zend_Cache in your application, and see with ab what makes your server works faster, basing on collected data.

Featured post

A map metaphor for architectural diagrams

It is a (two-dimension) representation of a pipe. The map is not the territory , but in software engineering terms they are models of it....

Popular posts