Archive for the 'Programming Language' Category

RubyBeans revisited (again) – Closures in Ruby

Tuesday, May 1st, 2007
Coffee Beans

A comment by Thomas Geis on my first RubyBeans post lead me to another rework of the RubyBeans metaprogramming example.

Thomas accurately points out:

I think the property should sit in a proxy-object, that does inform the listeners of its change. In your example, one could directly change the properties value from within the class without a call to the property_changed method.

This would be a concern for me. Isn’t it a concern for you?

Yes it is! I tried the proxy-object solution, but I am not satisfied with it for two reasons: the code get lengthy and inelegant, but mostly because the proxy-objects themselves aren’t protected from direct access.

I believe I have a nicer solution to protect the properties from direct access: closures. The first few lines of code remain unchanged:

class RubyBean

  def initialize
    @listeners = []
  end

  def register_listener(l)
    @listeners.push(l) unless @listeners.include?(l)
  end

  def unregister_listener(l)
    @listeners.delete(l)
  end

Now, observe how value is captured in the getter and setter blocks. The scope of the value local variable is the local block and the blocks passed in define_method. These blocks “close over” the value local variable.

  def self.property(*properties)
    properties.each do |p|
      value = nil
      define_method(p) { return value }
      define_method("#{p}=") do |new_value|
        return if value == new_value
        @listeners.each do |l|
          l.property_changed(p, value, new_value)
        end
        value = new_value
      end
    end
  end
end

Finally, here is an example of how RubyBeans would be used (were they not a Java idiom shamelessly ported for illustration purposes). The impotent_name= method cannot affect the name property, it will create a name instance variable, unrelated to the property.

class SimpleBean < RubyBean
  property :name, :firstname
  
  def impotent_name=(new_name)
    @name = new_name
  end
end

class LoggingPropertyChangeListener
  def property_changed(property, old_value, new_value)
    print property, " changed from ",
      old_value, " to ",
      new_value, "\n"
  end
end

test = SimpleBean.new
listener = LoggingPropertyChangeListener.new
test.register_listener(listener)
test.name = "Parker"
test.firstname = "Charlie"
test.firstname = "Maceo"
test.unregister_listener(listener)

Let me know if you spot something else!

Ozonesoft.net

Friday, March 16th, 2007

I am proud to announce the launch of my professional web-site: Ozonesoft.

RESTful Rails presentation

As a bonus, you can download the slides of the RESTful Rails presentation I gave at the Ruby Tuesday meetup this week, in Dublin. I hope you’ll enjoy reading it as much as I enjoyed writing it.

Ruby Ireland first meet-up

Tuesday, October 24th, 2006

It took us some time to organize, but we finally had our first Ruby Ireland meet-up last night. The event took place in Mulligan’s on Poolbeg Street, a pub notorious for serving one of the best pint of Guinness in Dublin… an aspect we all appreciated!

Mulligan’s on Poolbeg Street
Picture by Dave Bushe AttributionNoncommercialNo Derivative Works All rights reserved.

Seven Rubyists turned up for this introductory meet-up. One half were professional users, the other half… envious! Unsurprisingly, Rails was the main topic of conversation, but we also touched on Ruby meta-programming, a personal favorite.

I really enjoyed this meet-up. I don’t know whether it was the night out — a rare occasion when you’re the proud father of two young monsters — or whether it was the friendly and passionate people who turned up, but one thing is sure: I’m looking forward to the next Ruby Ireland meet-up!

technorati tags:, , ,

Plugging Python decorators

Friday, October 20th, 2006

For the last few weeks, I have been having very interesting discussions with a work colleague on a wide set of topics ranging from computing to philosophy and family life. He is a smart, passionate and knowledgeable developer and an avid learner. I tried to convince him to start blogging and I am glad to see he has taken the plunge: ladies and gentlemen, give a warm welcome to Muharem Hrnjadovic!

PythonHis opening salvo is a three part mini-study of Python decorators: check out part one and part two on his blog. Before you ask, part three is in the making and will be available shortly.

technorati tags:,

Practical Common Lisp

Wednesday, October 18th, 2006

Practical Common LispLast Sunday, browsing the bookshops in town, “Practical Common Lisp” by Peter Siebel caught my eye. I remember reading it online about a year ago. It allowed me to rediscover Lisp, since, to my regret, I had to bid farewell to the programmable programming language when I left college. It might have been nostalgia but I thoroughly enjoyed this book. Thanks to Peter Siebel! I had no hesitation, I bought the hardcover straight away. I can only recommend it highly for anyone wanting to learn Lisp.

This post would not be complete without pointing you to Paul Graham’s “On Lisp”.

Writing code with style!

Wednesday, August 16th, 2006

If you want to improve your coding style, I have got a little gem of a book for you! I discovered it thanks to Stéphane Ducasse and his great collection of free Smalltalk books. It was written 10 years ago by Edward Kilmas, Suzanne Skublics and David A. Thomas (yes, Pragmatic Dave, from Pragmatic Programmer and Pickaxe fame) and it deals with writing Smalltalk with style.

It is aptly titled Smalltalk with Style.

The Smalltalk focus might not be of interest to you — although a bit of Smalltalk cannot hurt a serious programmer! — but the style guidelines are invaluable and can be easily adapted to other languages or incorporated into a coding standard.

technorati tags:, , ,

Build Io on Fedora Core 5

Thursday, July 27th, 2006

Following in my own footsteps — yes, it is a recursive process — here are the steps required to install Io on Fedora Core 5.

sudo yum install freeglut-devel pcre-devel libevent-devel

Once again, libsgml needs a special treatment:

> wget http://www.hick.org/code/skape/libsgml/libsgml-1.1.4.tar.gz
[...]
> tar xfz libsgml-1.1.4.tar.gz
> cd libsgml-1.1.4
> ./configure
[...]
> make

At this point, you will need to edit the Makefile. Replace:

install -m 644 -o root -g root --directory /usr/local/include/sgml

by:

install -o root -g root --directory /usr/local/include/sgml
install -m 644 -o root -g root include/Variant.h \
    /usr/local/include/sgml/Variant.h

Save your modifications and proceed with:

> sudo make install

Finally, to download, build and install Io:

> sudo yum install darcs
[...]
> darcs get http://www.iolanguage.com/darcs/Io
[...]
> cd Io
> make
[...]
> sudo make install

Enjoy Io!

technorati tags:, ,

Io podcast

Thursday, July 27th, 2006

Rodney Ramdas, from pinupgeek, recorded the first episode of the Io podcast. His guests are Steve Dekorte, Io’s creator, and Jonathan Wright (aka quag) who does the night shift. It can’t get any better in the Io world!

Good luck Rodney for the podcast!

technorati tags:,

Build Io on Ubuntu Dapper

Thursday, July 27th, 2006

The Io language has a brand new build system. Gone is the static linking, Io is now dynamically linked. I believe the build system is far better than its predecessor.

It will need a couple of iterations to iron out a couple of problems. The detection of the dependencies for the bindings needs a small revision: it only checks for the libraries, not the header files. This is problematic on debian based system where, traditionally, a library X is in a package named libX and the header files in libX-dev.

If you want to experience Io on Dapper, you will have to do the following:

> sudo apt-get install build-essential
  libsqlite0-dev
  libpcre3-dev
  libfreetype6-dev
  freeglut3-dev
  libgmp3-dev
  libncurses5-dev
  libpng12-dev
  libtiff4-dev
  libevent-dev
[...]
> sudo ldconfig

To get the SGML binding working, you will have to get your hands dirty with libsgml. Here is how:

> wget http://www.hick.org/code/skape/libsgml/libsgml-1.1.4.tar.gz
[...]
> tar xfz libsgml-1.1.4.tar.gz
[...]
> cd libsgml-1.1.4
> ./configure
[...]
> make
[...]

Before going any further, you need to edit the Makefile and change the first line of the install target from:

install -m 644 -o root -g root --directory /usr/local/include/sgml

into this:

install -o root -g root --directory /usr/local/include/sgml
install -m 644 -o root -g root include/Variant.h \
    /usr/local/include/sgml/Variant.h

Don’t ask… Finally, to install libsgml in a relatively clean way, I suggest using checkinstall like this:

> sudo apt-get install checkinstall
> sudo checkinstall

The stage is ready for Io:

> sudo apt-get install darcs
[...]
> darcs get http://www.iolanguage.com/darcs/Io
[...]
> cd Io
> make

May the cloning begin!

technorati tags:,

Updated on 05/09/06: fixed typo, thanks to Jesse’s comment.

Producing and maintaining high-quality code

Wednesday, April 26th, 2006

So much bad and ugly code is being spewed out every day all over this planet that entire websites are dedicated to the preservation of the worst specimens. In this post, I will show you simple ways to produce and maintain high-quality code because, firstly, this is one way of achieving Internet stardom that you probably want to avoid and secondly and more importantly, you know how painful it is to have to maintain bad code.

I will start by a disclaimer, using Douglas Adams words:

The problem with designing something completely foolproof is to underestimate the ingenuity of a complete fool.

You can follow all the tips in this post and still end up with bad code, but you would have to be a very crafty fool!

1. Understand the problem

If this sounds like a duh-ism, that is because it is one. If you do not understand what the code is supposed to do, you will not get it right. Before you start coding, whether you face a blank sheet or whether you are maintaining code, sit down and think: what problem am I trying to solve here.

2. Write unit-tests

I could almost have numbered it 1bis. Unit tests show and validate how the code is supposed to be used. Write the tests first if possible — unless you can get your hands on a time-machine, this is not an option when doing some maintenance. The quality of your interfaces will improve dramatically because you will design them from their user’s point of view.

3. Talk to your cardboard friend

How many times were you stuck on a problem, decided to seek help from a nearby colleague, explain the situation and bingo! the solution became obvious. Your colleague hasn’t even had time to pronounce one word, he probably didn’t even understand the question. Articulating the problem solved it. My nearby colleague calls this the “cardboard friend” because people drawn on cardboard tend to have the property of listening without interrupting.

4. Enforce a coding standard

I previously wrote about this but just in case you missed it: you need a coding standard to make your code homogeneous because reading code is hard enough, you do not need the distraction of multiple coding styles. Once you have a coding standard, use tools to enforce it. In Java, checkstyle rocks and if you use eclipse, be sure to check out this plugin. There are similar tools in most languages, use them! At first configure them to be a complete and utter pain and then relax the rules you believe are damaging.

5. Use code analysis tools

Use any tool you can find to study and analyze your code. If the language you are using is compiled, turn on all warnings on the compiler: use -Wall when you use gcc, open the preferences in Eclipse and activate most warnings for the Java compiler (be pragmatic). Use any lint-clone you can put your hands on for your language. Here are the tools I recommend for Java: JDepend to measure the quality of my abstractions and to avoid cyclical dependencies, PMD to identify potential bugs and potential optimizations, FindBugs to (coincidentally) find bugs. I should mention Checkstyle again since it can also detect bug patterns. The situation is simple: the more code analysis tools you run on your code the more you will be able to fix problems before they bite you.

6. Use a continuous integration system

I will unleash my secret finishing move on the next guy who tells me: “but it works on my machine”. A continuous integration system is a referee. If the ref says the build fails because it is broken or because some test fails, it’s because it is. So, go fix it. The ref is always right even when “it works on my machine”. How does it do that? At regular intervals, it tries to build the latest version of your code and if anything goes wrong, it fires notifications — generally emails — to whoever is concerned. Receiving these notifications is not such a bad news: you have identified a problem in your code. Use your continuous integration system to run the code analysis tools and fail the build if these tools report problems. You can use CruiseControl, AntHill, DamageControl or write your own with cron+make+sendmail, but please use a continuous integration system.

7. Write less code

Aspire at writing code like a Zen master writes a Koan:

Monk: Does a dog have Buddha nature or not?
Zhaozhou: Wú.

There are two principles to assist you in your quest for minimalist code: KISS and DRY. “Keep It Simple Stupid”: do what is required and no more. Focus on a clean and simple implementation. “Don’t Repeat Yourself”: avoid duplicating code. Refactor mercilessly. This will decrease the size of your code-base, which is a Good-Thing™ because the less code you write, the less bugs you write.

8. Performance is overrated

I will probably have a contract on my head after this point, that’s what blogging is about, no? Writing fast code is a two step process:

  1. get the code to work,
  2. stop.

In case this was unclear: do not optimize the code. In the vast majority of cases, the code you are about to optimize is not a bottleneck. Use a profiler on a system running realistic data and identify the bottlenecks. Only then can you start working out how to eliminate them. Very often you will not have to change a single interface, only the implementation will require changes.

9. Read, read, read

Read books about software development. You must read the GoF book about Design Patterns and put it to good use. You must pick up Martin Fowler’s Refactoring, Code Complete by Steve McConnell. There are countless others. One of the first book to really open my eyes on developing good code was Writing Solid Code by Steve Maguire.
Read books about other programming languages too, you will frequently discover programming concepts that you might be able to port to your environment.

10. Use common sense

Common sense is your best friend to beat bad code and it’s free! Common sense is what dictates the previous nine points.

I hope you found these tips interesting and entertaining too! I am looking forward to your comments. I leave you with Zhaozhou to conclude this post: Wú!.

technorati tags:, ,