{ |one, step, back| } 134 to 143 of 193 articles Syndicate: full/short

Perl 6 -- Apocalypse 12   17 Apr 04
[ print link all ]

The Once and Future Perl

In February 2001, Larry Wall came to Cincinnati to (amoung other things) give a talk on the future directions that the Perl language would be taking in version 6.

I had switched to using Ruby (from Perl) about 6 months earlier at that time, and I had a chance to talk to Larry about the changes in OO support that he wanted in Perl. I remember him commenting that Perl5 made OO possible, but not necessarily convenient.

In his Apocalypse series, Larry describes the direction Perl 6 will be taking in several areas. Three years after that talk, Apocalypse 12 is available, and it addresses the details of Object Orientation in Perl 6.

I just want to point out that all the examples in this blog entry are directly from the apocalypse.

Objects in Perl 6

I skimmed the article last night and jotted down some notes. You will need to read the apocalypse yourself for any substantial details (its a long article, 20 pages in all). I’m just going touch on some highlights and first impressions.

Objects in Perl 5 were built out of the existing language framework. Blessing was the only new piece added to Perl to support objects, hash, packages and namespaces were all existing Perl concepts. And although it worked, it left the Object Model of Perl very open to variations.

Perl 6 adds more language support for direct support of objects, and leave less to programmer choice. Here is a point object in Perl 6:

    class Point {
        has $.x;
        has $.y is rw;
        method clear () { $.x = 0; $.y = 0; }
    }

Notice the keywords for class and the declaration of attributes $.x and $.y. The $.x attribute is publicly readable, and the $.y is publically writable as well. Private attributes can be declared with a colon instead of a period (e.g. $:z).

Methods are part of the class declaration now and are syntactically differentiated from normal subroutines by using the "method" keyword.

ISA vs HASA

In OO circles it is said that HASA relationships should be modeled by composition and ISA relations by inheritance. Although I find that saying to be a bit simplistic, it is cool that Larry makes that connection explicit by his choice of keywords. Did you notice in the above example that the attributes were introduced by the keyword has?

So its not surprising that inheritance is introduced with the is keyword. Here’s another simple example building on the previous one:

    class Point3d is Point {
        has $:z = 123;
        method clear () { $:z = 0; next; }
    }

The is keyword is overloaded (this is Perl after all). Traits are also declared using the is keyword. That leads to interesting code like:

    class Moose is Mammal is stuffed is really(Hatrack) is spy(Russian) {...}

Roles

Although Perl 6 will support inheritance (single or multiple), it also contains the idea of Roles. My impression of a Role is that is a cross between Ruby modules and Java interfaces.

Roles look a lot like classes, but they cannot be instantiated. Roles cannot inherit from classes, but they can be composed with other roles.

Here is an example role. Notice that the method feed depends upon the method call should should be defined in the final objects.

    role Pet {
        method feed ($food) {
            $food.open_can();
            $food.put_in_bowl();
            .call();
        }
    }

Roles are attached to classes with the does keyword:

    class Dog {
        is Mammal;
        does Pet;
        does Servant;
        does Best::Friend[Man];
        does Drool;
        ...
    }

So far Roles look very much like Ruby modules. However, here is a twist. If the methods in roles are only declared instead of defined, then the Role specifies the methods expected to be implemented in the class. One final example.

    role Pet {
        method feed ($food) {...}
        method groom () {...}
        method scratch (+$where) {...}
    }

The {…} construction means that the body of the method is defined elsewhere.

Stuff I Left Out

This Apocalypse runs 20 pages. Its obvious that I skipped over a lot of material. It seems like the OO support in Perl 6 is much better than Perl 5. The object module is very flexible (a good thing), but also rather complex (a not so good thing). Larry addresses some really interesting problems (such as multiple dispatch), and it will be interesting to watch to see if the features really work together or not.

Am I switching? No, not really. I really much prefer the much simplier object model (and syntax!) provide by Ruby. But I will be watching.

Some Great Quotes

Larry is great for generating good quotes. I’ll end this entry with a few quotes that struck me.

It has often been claimed that Perl 5 OO was "bolted on", but that’s inaccurate. It was "bolted through", at right angles to all other reference types, such that any reference could be blessed into being an object. That’s way cool, but it’s often a little too cool.

Here’s another one:

Some people will be surprised to hear it, but Perl is a minimalist language at heart. It’s just minimalistic about weird things compared to your average language.

And speaking of chosing a keyword to distinguish typing from subtyping:

On the other hand, a bit confusingly, it looks like subtyping will be done with the "type" keyword, since we aren’t using that word yet.

Closing Joke

For some reason, I found this extremely funny:

Biologist :What’s worse than being chased by a Velociraptor?
Physicist :Obviously, being chased by an Acceloraptor.


comments

More New Looks   14 Apr 04
[ print link all ]
I was chatting with Chad Fowler last night on AIM. Amoung other things, Chad demonstrated his MovableStyle template for Rublog. It is pretty neat. You can download stylesheets from MovableStyle intended for MovableType and use them with the latest version of Rublog. Chad’s website uses a MovableStyle stylesheet.

Today Dave Thomas mentions the Moveable Style support in a blog entry. So at this point, I had to experiment!

The following links demonstrate the MovableStyles stylesheets for this website. Click on the link and see this site transformed using the stylesheet. Have fun.

  • ModernLines — Very nice looking.
  • Trendy — I like this one, except for the strange super-sized calendar.
  • Boxed — This one is too busy for my taste.
  • SlashDot — Yes, it is a copy of our favororite geek website.
  • Chad Fowler — Ok, I stole Chad’s style sheet just to show it could be done. I really like this style.
  • Original Rublog — This is the original, out of the box color scheme that comes with Rublog. I find the colors a bit … jarring. But my daughter likes it.
  • Default — The default look and feel for this site. It feels a bit plain now.

All but the last two styles were downloaded from MovableStyles.

Correction: Chad tells me that his style is a MovableType style, but it was not downloaded from the MovableStyle web site.



comments

New Site Look   09 Apr 04
[ print link all ]
I’ve updated the site with several new items.
  • First, a new CSS scheme. I think it makes the pages look a little sharper.
  • A wiki is now available for feedback. See it at onestepback.org/cgi-bin/osbwiki.pl. There’s not much in the wiki yet, but I intend to use it for feedback and posting sample code snippets. Someone on the Rake mailing list wished to have a place for collecting sample Rakefiles, and the wiki would work nicely for that.
  • The wiki supports an RSS feed at onestepback.org/cgi-bin/osbwiki.pl?action=rss

Hey! Look below! We already have a feedback link for this article.



comments

Ruby Module Spotlight: Session   27 Mar 04
[ print link all ]
Here’s a sweet little module from Ara T. Howard. It is called Session and will run a shell session under the control of a Ruby script. Standard output and standard error are captured by the session object and made available to the script.

How about a quick example …

  bash = Session::Bash.new
  stdout, stderr = bash.execute "ls"
  p stdout     # prints "trysession.rb\n"

The shell session created is persistent. Executing multiple commands in the session is like typing multiple lines into a real shell, the state is remembered from one command to the next. If you change the current directory, subsequent commands will execute in the new location. Environment variables set in the session will be remembered in later commands.

  bash = Session::Bash.new
  bash.execute "export GREETING=hi"
  out, err = bash.execute "echo $GREETING"
  p out    # print "hi\n"

If you pass an IO object to the session, it will append its output to that object.

  out = StringIO.new
  bash = Session::Bash.new
  bash.execute "ls", :stdout=>out
  bash.execute "ls ..", :stdout=>out
  p out  # prints the output from both "ls" commands.

One possible use of Session is to test command line scripts where you wish to check both standard output and standard error independently.

  class TestVersion < Test::Unit::TestCase
    def test_install
      out = StringIO.new
      bash = Session::Bash.new
      bash.execute "export GEMPATH=#{TESTDIR}"
      out, err = bash.execute "bin/gem --install testgem"
      assert_equals 0, bash.exit_status
      assert_equals "", err
      assert_equals EXPECTED_OUTPUT, out
      assert_test_gem_installed
    end
  end

You can find Session at www.codeforpeople.com/lib/ruby/session/


comments

Some Things are Hard to Test ... ?   26 Mar 04
[ print link all ]
Perryn Fowler has a few words of wisdom to share on what can and cannot be tested. I especially like his closing remark.

His remarks are short, so I have reproduced them here in full.

some things you just can’t test
Rubbish. Think harder.
Of course some things are very difficult to test, and in some cases the effort is not worth it when compared to the amount of risk it would mitigate - but that is a business decision rather than a purely technical one.
You can make this decision a lot easier by not putting important behaviour in things that are hard to test

comments

Martin Fowler on Specification by Example   23 Mar 04
[ print link all ]
Martin Fowler shares some thoughts on Specification by Example and compares it with Design by Contract. I’ve written on DbC and Test First before, but Fowler expresses his ideas so much better.
comments

Using WEBrick   19 Mar 04
[ print link all ]
Several folks (e.g. Kevin Altis, Aaron Brady) have written about a single line web browser in Python. I wondered what it would look like in Ruby. Here’s one answer…
  ruby -rwebrick -e 'WEBrick::HTTPServer.new(:Port=>8000,:DocumentRoot=>".").start'

Since WEBrick defaults to port 80 and doesn’t use the current directory as the document root by default, we have to add that information to the command line.

Although interesting, I find the following script more useful than a single line command. I often generate HTML docs on a machine at work that doesn’t have a web server, nor file system that is available to my browser’s "file:" protocol. So I fire up the "servefiles.rb" script below.

  #!/usr/local/bin/ruby
  require 'webrick'
  include WEBrick

  dir = Dir::pwd
  port = 12000 + (dir.hash % 1000)

  puts "URL: http://#{Socket.gethostname}:#{port}"

  s = HTTPServer.new(
    :Port            => port,
    :DocumentRoot    => dir
  )

  trap("INT"){ s.shutdown }
  s.start

Notice that the port is calculated from a hash function on the directory name. This allows me to run multiple mini-webservers in different directories. The script prints out the URL (with port number) when it starts, so I just cut and paste the URL into the browser to see the served files.

How do you use WEBrick?


comments

Pretty Rublogs   19 Mar 04
[ print link all ]
I see a number of Rublog users have upgraded their blogs look and feel. (See Dave Thomas, Chad Fowler and Glenn Vandenburg). It leaves this site looking a wee bit plain now.

Hey Guys! Care to share your template and CSS files?


comments

RubyGems Alpha 0.2.0 Released   19 Mar 04
[ print link all ]
I grabbed the latest version of RubyGems and typed:
    traken$ sudo gem --remote-install log4r
    Successfully installed log4r version 1.0.5

With one command, log4r was downloaded and installed without hassle or fuss. This is way cool.

There is a lot of work to be done on RubyGems, but making Ruby project installations this easy is great.


comments

Some Pointers   13 Mar 04
[ print link all ]
I have not updated this Blog for over a month. It has been real busy around here. I have some ideas I want to share, but I think I’ve run afoul of Charles Miller’s #1 blogging rule. So I’m just going plunge into this posting by pointing out a couple of interesting reads I’ve found lately.

But First, Some Apologies

Yes, my site was down for a few days in February. I didn’t notice it right away, and when someone at work pointed out they couldn’t get to onestepback.org I had to wait to fix it until I got home. Even then, I thought it was only down for the day. It wasn’t until I reviewed the web stats for February did I realize that it was down for at least three days.

Sorry. It turns out that the copy of apache servicing http requests had crashed and burned. The ssl server was still up so remote access to my mail was OK. I just didn’t notice that the http server was down (see, I really was busy). Nevertheless, we now have some monitoring software in place so simple crashes shouldn’t cause extended outages any more.

Directing VS Enabling

Static verses Dynamic Typing. Checked verses Unchecked Exceptions. The battle rage on (and I’ve taken part in my share of them). Martin Fowler has some keen insight into the nature of the proponents of each side of the debate. He calls it the difference between a Directing attitude and an Enabling attitude. Directors wish to make the computing environment as safe as possible and willing accept restrictions to achieve that goal. Enablers desire flexibility above (in their view unneeded) safety, and will chaffe unagainst restrictions. Read Martin’s writeup, he explains it much better than I do.

I’ve landed on both sides of the debate in the past. Lately I’ve found myself on the enabler side of the equation more often than not.

When Generic’s Aren’t

Bruce Eckel has some surprising insight on the use of generics in Java (available in Java 1.5). For those who enjoy the ad-hoc polymorphism available in C++ generics are going to be surprised by Java’s version. If Eckel is correct, then generics look like they will be great for making generic containers and little else.

See Bruce’s article for details.

And More on Latent Typing

Speaking of the Static/Dynamic typing debate, the feedback page for Eckel’s Generics article, a commenter is defends the need for interfaces with the following comment:

In java, the symantics of a method are not bound to its name, so much as they are bound to the interface the method belongs to.

Bruce responds with a followup article on Latent Typing, but I would like to add my two cents here.

Java interfaces are more about syntax than semantics. They insure that implementing classes have the proper methods defined with the proper number and type of arguments, and that the methods actually do return a value of the appropriate type. But that’s it. Interfaces do nothing to support any meaningful semantics about the methods.

If you are interested in language support for semantics, I suggest you take a look at Eiffel. When you define a interface in Eiffel (which Eiffel would call a deferred class), you not only specify the argument list for the method, you also specify the promises to which the method implementor must adhere. This set of promises (the semantics) is called a contract and leads to the concept of Design by Contract.

Even if you never program a line of Eiffel code, understanding Design by Contract is a useful skill for a developer.

Speaking of Design by Contract

And that leads us to our final posting. Artima has published a series of interviews with Bertrand Meyer, the designer of Eiffel and Design by Contract. The interviews are worth reading (here is part 4, you can find links to the other parts from there).

I find that I don’t always agree with Meyer, but when I do disagree, I think through my position very carefully.

All for Now

I’ve run out of time. Hopefully it won’t be so long before I post again.


comments

 

Formatted: 21-May-12 10:39
Feedback: jim@weirichhouse.org