Wednesday, May 1, 2013

[Blog] Great use of Null Object pattern

Last weekend, I watched a talk Code Smells: Your Refactoring Cheat Codes by John Pignata from MountainWest RubyConf 2013. I was really enjoyed with it. One of the technique that I really like is his use of Null Object pattern. Even though, I know this pattern for long time, but in the situation he was in, I would not be able to come up with the solution like that.

Almost at the end of the talk, his code came to the state that he has jobs and PushDaemon that pushing jobs to the worker. Because a job returned from factory can be nil, he needs to check and allow only non-nil job to be pushed. This is a well-known use case for Null Object Pattern. He modified factory to  return NullJob instead of nil. Now his PushDaemon doesn't need to check for nil anymore.

The code was cleaner without nil checking but pushing null job to worker is not so efficient. How can we avoid pushing NullJob to the worker without checking for nil? That was the time he showed a great technique. Flipping push method (<<) in PushDaemon which was send to worker list to send to job with the opposite direction (>>) and pass worker list as an argument instead. Then implements >> for all the jobs to push itself to worker list except for NullJob. >> of NullJob does nothing. At the end, everything fall cleanly and efficiently.

I highly recommend you to check out his talk for other great refactoring techniques yourself from the link beginning of this blog or on his blog directly.

No comments:

Collectd PostgreSQL Plugin

I couldn't find this link when searching with google https://www.collectd.org/documentation/manpages/collectd.conf.html#plugin-postgresql