Friday, October 23, 2009

Observe this!

Ch. 2 from HFDP - Part 01 of 03

Target Audience: This series is pitched at developers interested in Object Oriented Design Patterns using the Moose framework in Perl. I cover the examples from the Head First Design Patterns book, replicating Java implementation in Moose. You need to obtain a copy of the book, which is not hard to come by.


When I was a kid, my dad would tell me that what keen observation powers are what makes a person excel in analysis. That is borne out by Arthur Conan Doyle's prodigious creation, Sherlock Holmes.

The Observer pattern thus starts with much going for it!

It is one of my favorite patterns. Chiefly because dynamic interplay of objects that send and receive messages is a very powerful paradigm for making things happen. And the Observer pattern achieves just that!

The folks at HFDP present this as a one-many relationship between a 'Subject' that upon changing state sends notification to 'Observers' that have subscribed to listen-in. Think of a many-many relationship. It is just a collection of one-many relationships. Now think of an Observer that also implements the Subject interface. (We'll come to interfaces in a minute. Just pretend it means an Observer can behave like a Subject.) Now you have Object-Oriented Utopia. Or at least, a democracy where empowered objects send, receive and cascade messages to each other, subscribing or unsubscribing at will.

At HFDP, the story starts with a Weather Station API. The Weather Station captures 3 variables: temperature, pressure and humidity. Any time the measurements change, various Display Classes that plug-in to the Weather Station API are notified so as to render the latest information on the weather. The business model is the Weather Station company charges for Display Elements that plug-in to their API.

(Sounds familiar? Think of the Facebook API.)

For the rubber hitting road, this means the Observer pattern is in business!

A draft Weather Station can be sketched as follows:

package WeatherData;
use Moose;

has 'temperature' => (
is => 'rw',
isa => 'Value',
);

has 'humidity' => (
is => 'rw',
isa => 'Num',
);

has 'pressure' => (
is => 'rw',
isa => 'Num',
);

sub measurementsChanged {
# plug-in API
}

This bit is self-explanatory.

The principle underlying the Observer pattern is that the Subject holds copies of (references to) registered Observers. The Subject's responsibility is to provide methods for registration and un-registration. The Observer's responsibility is to make available an 'update' method that the Subject can invoke on all registered Observers. Simple?

Here then, is the abstract Subject:

package Subject;
use Moose;

sub _registerObserver {};
sub removeObserver {};
sub notifyObservers {};

and the prototypical (i.e. abstract) Observer

package Observer;
use Moose;

sub update {};

Think of these prototypes as 'roles' - little packets of functionality which allow re-use of code. Classes can be composed with them - or in Moose parlance, Classes consume roles. Do you see how this differs from conventional inheritance? The leitmotif is flexibility in terms of code re-use, regardless of the specifics of implementation. As you shall see, I do indeed use multiple inheritance to achieve composition.

That is because Perl (and Moose) support multiple inheritance. Java doesn't, and there composition with roles (the Java term is 'interfaces') needs to follow a stricter syntactic demarcation from inheritance.

The last prototype (or role, or interface, or abstract class) is:

package DisplayElement;
use Moose;

sub display {};

You got to love how easy that was!

Let's compose the Subject role into the Weather Station. Note the use of the Method Modifier 'after' to hook into the methods of the abstract implementation.

package WeatherData;
use Moose;

extends 'Subject';

has 'observers' => (
is => 'ro',
isa => 'ArrayRef[Observer]',
default => sub {[]},
predicate => 'has_observers',
);

has 'temperature' => (
is => 'rw',
isa => 'Value',
);

has 'humidity' => (
is => 'rw',
isa => 'Num',
);

has 'pressure' => (
is => 'rw',
isa => 'Num',
);

after '_registerObserver' => sub {
my $self = shift;
my $thisObserver = shift;
push @{ $self->observers }, $thisObserver;
print "Now has: ", scalar @{ $self->observers }, " observers.";
};

after 'removeObserver' => sub {
my $self = shift;
my $deletionIndex = shift;
my $cutObserver = splice @{ $self->observers }, $deletionIndex, 1;
$cutObserver->clear_Subject;
print "Now has: ", scalar @{ $self->observers }, " observers.";
};

after 'notifyObservers' => sub {
my $self = shift;
foreach my $thisObserver (@{ $self->observers }) {
$thisObserver->update($self->temperature,
$self->pressure,
$self->humidity);
}
};

sub measurementsChanged {
my $self = shift;
$self->notifyObservers;
}

sub setMeasurements {
my $self = shift;
my ($temperature, $pressure, $humidity) = @_;
$self->temperature($temperature);
$self->pressure($pressure);
$self->humidity($humidity);
$self->measurementsChanged;
}

What have we achieved? We have composed the 'Subject' role into the'WeatherData' class and added a slot that lends this class a container for subscribers. Note how the notification is applied by iterating over contents of 'observers'. Note also that notification is initiated by the method 'setMeasurements' of the Weather Station, the chain of command being: 'setMeasurments' to 'measurementsChanges' to 'notifyObservers'. Now it remains to define the display. And that's coming up in Part 2.
~ * ~

All code in this series may be downloaded from:
http://sites.google.com/site/sanjaybhatikar/codeunquote/designpatterns-1

Wednesday, October 21, 2009

The State of Moose.

Ch. 10 from HFDP

Target Audience: This series is pitched at developers interested in Object Oriented Design Patterns using the Moose framework in Perl. I cover the examples from the Head First Design Patterns book, replicating Java implementation in Moose. You need to obtain a copy of the book, which is not hard to come by.


Target Audience: This series is pitched at developers interested in Object Oriented Design Patterns using the Moose framework in Perl. I cover the examples from the Head First Design Patterns book, replicating Java implementation in Moose. You need to obtain a copy of the book, which is not hard to come by.

I like to talk of State Machines. Because they are so natural. I like to think about interesting elements the world about me in terms of State Machines. Take girlfriend or spouse, for instance, their behavior depends so much on their state..

Jokes apart, what I've hinted at is the essence of a State Machine. Behavior that is regulated by State. Or stated in Object-Oriented parlance, the implementation of a method varies according to the state of the object.

Obviously, that leaves us but one choice for dealing with these Jekyl-Hydesque objects - to encapsulate behavior in 'State' classes. And that's all about to make sense.

The brains at Head First cite the example of Gumball Machine which has various methods like 'insert quarter', 'turn crank', 'dispense gumball', etc., which all depend on the state of the machine, i.e. if the machine has a quarter in the slot then turning the crank delivers a gumball. To illustrate this, the folks at HFDP show a state diagram. The states are circles and the arrows are actions (methods) that typically produce a change of state. Neato!

(Now if I could do this with the women in my life... sigh!)

The implementation consists of encapsulating behavior in an abstract class 'State' and providing method definitions in concrete classes corresponding to each of various possible States. For example, 'turning crank' when the machine state is 'has quarter' leads to dispensation of a gumball but when there is 'no quarter' or the machine is 'sold out' doesn't produce the same result.

Here then is the State class:

package State;
use Moose;
has 'gumballMachine' => (
is => 'rw',
isa => 'GumballMachine',
predicate => 'has_gumballMachine',
);

sub insertQuarter {};
sub ejectQuarter {};
sub turnCrank {};
sub dispense {};

When the machine has a quarter, the state is 'HasQuarterState'.

package HasQuarterState;
use Moose;
use GumballMachine;

extends 'State';

sub insertQuarter {
print qq{You cannot insert a quarter now.};
};

sub ejectQuarter {
my $self = shift;
print qq{Here's your quarter back.};
$self->gumballMachine->currentState($self->gumballMachine->noQuarterState);
};

sub turnCrank {
my $self = shift;
print qq{You turned...};
$self->gumballMachine->currentState($self->gumballMachine->soldState);
};

sub dispense {
print qq{No gumball dispensation.};
};


Notice - the action only happens upon two events: turning the crank and eject. The rest of the methods just mumble on standard output.

Now here's the thing! The Machine (which we are about to see) delegates behavior to an object of the State class for implementation, according to current state. That means the Machine has got to hold objects of State class, one for each state. And each of these objects in turn own a copy of (i.e. reference to) the Machine. At any time, one (and only one) among the State objects of a Machine is set to the current state.

That's so something like this makes sense:

$self->gumballMachine->currentState($self->gumballMachine->soldState);

Notice how this action changes the current State of the Gumball Machine to a new State.

The underlying principle is Composition. It's something Beethoven did a lot of, before he started decomposing. The Machine is composed of States. Savvy?

Here then, is the Machine class:

package GumballMachine;
use Moose;

use State;

has 'hasQuarterState' => (
is => 'rw',
isa => 'State',
default => sub { HasQuarterState->new(gumballMachine => $_[0]); }
);

has 'soldState' => (
is => 'rw',
isa => 'State',
default => sub { SoldState->new(gumballMachine => $_[0]); }
);

has 'noQuarterState' => (
is => 'rw',
isa => 'State',
default => sub { NoQuarterState->new(gumballMachine => $_[0]); }
);

has 'soldOutState' => (
is => 'rw',
isa => 'State',
default => sub { SoldOutState->new(gumballMachine => $_[0]); }
);

has 'count' => (
is => 'rw',
isa => 'Num',
default => 0,
);

has 'currentState' => (
is => 'rw',
isa => 'State',
default => sub { $_[0]->{noQuarterState} },
);

sub releaseBall {
my $self = shift;
print qq{"Releasing a gumball.."};
$self->count($self->count - 1);
print $self->count." remaining.";
}

sub insertQuarter {
my $self = shift;
$self->currentState->insertQuarter;
}

sub ejectQuarter {
my $self = shift;
$self->currentState->ejectQuarter;
}

sub turnCrank {
my $self = shift;
$self->currentState->turnCrank;
}

sub dispense {
my $self = shift;
$self->currentState->dispense;
}

1;


A few notes on Moose:
1.
Note the keyword 'extends' for inheritance. The abstract class is simply implemented with empty methods.
2.
Note the use of default attribute to populate slots. The default holds a sub reference. For reference to self in the default definition, $_[0] applies.
3.
Note the use of delegation and composition. The Machine is composed of States and delegates actions to the object of State class representing its current state. These are extremely powerful concepts.
One area where I have found it useful to deploy these concepts is inter-operable document standards - when converting between standard XML namespaces. My target data-structure delegates parsing to a streaming SAX parser which packages information from the source file into neat parcels. The delegatee then ships out ready parcels to the target data-structure's container classes.
4.
I have used an abstract class instead of a role. Though roles, in general, are more strongly associated with composition, I believe this is largely a matter of semantics. Notice, I could have used the Method Modifier 'after' instead of over-riding methods from the abstract class. You will find Method Modifiers used in my latest code.

~ * ~

All code in this series may be downloaded from:
http://sites.google.com/site/sanjaybhatikar/codeunquote/designpatterns-1

Tuesday, October 20, 2009

Design Patterns in Moose

These days, design patterns are everywhere. And why not? Exposure is what shapes raw developer-material into greatness! And what better way to get exposure than through condensed experience in the form of Design Patterns - well-formulated problems and the pragmatic programmatic patterns that solve them!

Mind you, Design Patterns are a double-edged sword. The strength is also the weakness - too many patterns and one faces the classic problem known as over-fitting in the predictive modeling community, to wit, one becomes useless at doing anything that differs from what one has seen before.

The trick to design patterns is building this castle on a solid foundation of systems engineering. That is, knowledge of software systems and their interacting components. Practical knowledge of software systems. One has really got to be at a point, like Beethoven poised to write the 9th symphony, where all past work seems vaguely dissatisfying. Yes, work got done, but it could have been done better! Perhaps, the people maintaining that code-base you contributed to are complaining. Or there are faint but audible murmurs about how they wish they could just throw away that code-base and start from scratch.

You have got to base knowledge of Design Patterns on experience.

Thus forewarned, pardner, let me now roll-out before you my plan. You see, Design Patterns have been popularized in the Java world by a nifty book called "Head First Design Patterns" that features a hot chick on the cover at a flattering angle. And, about the same time, the Perl world is abuzz with Moose - a swanky post-modern object-oriented framework. Need I say more?

What this is about is implementing the Design Patterns - fully a Baker's dozen of them - in Moose-Perl. Now whaddya say to that?

The idea is not a one-one mapping between concepts in the Java and Moose worlds, but to demonstrate the effectiveness of the Moose framework. Or possibly the lack thereof, for this blog is objective. See, there is a lot of talk lately of how Perl is falling behind newer entrants like Python and Ruby. There is talk of how companies with an eagle eye on the bottom-line are moving away from Perl. And how, very soon, the only programmers in the Perl world are likely to be legacy coders.

That disturbs me. Because I really like Perl. Deep down, I feel a sense of well-being coding in Perl that I don't feel elsewhere. It is like Perl is my native tongue, aligned with my thought patterns. When I code in Perl, code seems to flow out of my fingers from the thoughts abuzz in my mind.

And that is fun! Fun that I would like to share with others in the world. Anyone have a pic of Larry's daughter? I hear she is hot! Just kidding folks, testing to see that you are still with me.

This series isn't going to be spoon-feeding. Neither is it an introduction to object-oriented programming. Where it seems appropriate, I shall point out certain object-oriented features to rave about. Or rant at abuse of the principles underlying these features. The idea, as always with this blog, is that you - the intelligent, handsome, sexy reader - try out stuff. And have fun doing it. I'll give you enough to keep you going.

Watch out for the Moose!

~ * ~

All code in this series may be downloaded from:
http://sites.google.com/site/sanjaybhatikar/codeunquote/designpatterns-1

Notes on Syntax Highlighting

http://pleasemakeanote.blogspot.com/2008/06/posting-source-code-in-blogger.html

Has very clear instructions.

Exception Handling: Part 05 of 05

Part 5: Exception Handling Best Practices

Target Audience: This pitch would interest a developer interested in the Exception Handling Best Practices in Perl. This series starts with basic exception handling and adds complexity, ending with pragmatic Best Practices recommendation.

You have put up with a lot so far and here is where it all becomes worthwhile. Best Practices, in a numbered list. Now, how much is that worth to you? (I accept checks.)

  • Use Exception::Class. Enuf said!
  • Use Fatal.pm for core perl functions:
eval { open(FH, "/non-existent/file") };
warn($@) if $@;
eval { close(FH) };
warn($@) if $@;
eval { chdir("gobbledegook") };
warn($@) if $@;
eval { unlink("/etc/password") };
warn($@) if $@;
eval { socket(SOCK, AF_INET, SOCK_STREAM, getprotobyname('tcp')) };
warn($@) if $@;
  • Define a $SIG{__DIE__} to turn string exceptions into objects
  • Trap exceptions using the 'eval' block and conditions set on the special variable $@
  • ALLOW EXCEPTIONS TO PROPAGATE!
  • Handle only an exception of an expected type.
  • To log all exceptions, use main() wrapped in exception handler.
  • Use Fatal qw(:void) in Perl 5.6+
~ * ~

All code in this series may be downloaded from:
http://sites.google.com/site/sanjaybhatikar/codeunquote/exceptionhandling-1

Exception Handling: Part 04 of 05

Part 4: Tying up loose ends with the $SIG{__DIE__}

Target Audience: This pitch would interest a developer interested in the Exception Handling Best Practices in Perl. This series starts with basic exception handling and adds complexity, ending with pragmatic Best Practices recommendation.

local $SIG{__DIE__} = sub {
my $e = shift;
if ($e->isa('My::Exception::Base')) {
die $e;
} else {
die My::Exception::Base->new($e);
}
};

All this does is cast an exception into an Exception::Class type. If already that, then simply thrown as exception with 'die'.

Clever, huh? This works because $SIG{__DIE__} is called invisibly FIRST, BEFORE ANYTHING ELSE when an exception is thrown, and the program continues to 'die' upon the handler's return. (Hence, DO NOT trap exceptions with $SIG{__DIE__} !)

Why is the $SIG{__DIE__} handler declared local?

Sunday, October 4, 2009

Barbershop Wisdom

"But the problem with y'all cats today, is that you got no skill. No sense of history. And then, with a straight face, got the nerve to want to be somebody. Want somebody to respect you. But it takes respect to get respect. Understand? See, I'm old. But, Lord willing, I'd be spared the sight of seeing everything that we worked for flushed down the drain by someone who don't know no better or care."

I like to reflect on how well that applies to software development. Candidate interviews particularly give food for thought.