Friday, October 14, 2011

Object oriented versus functional interface

I use DateTime::Format::W3CDTF for parsing my dates:

my $w3c = DateTime::Format::W3CDTF->new;
my $dt = $w3c->parse_datetime( $date_string );

I wish it was:

my $dt = DateTime::Format::W3CDTF->parse_datetime( $date_string );

and that the library created the parser on the fly as needed. It's not only less typing - but also much simpler mental model. This simpler model is sometimes too simple - for example if you parse a lot of dates then sparing the parser creation each time can make a difference.

I think the optimal thing to do is provide two APIs - like JSON - a functional one:

$perl_hash_or_arrayref = decode_json $utf8_encoded_json_text;

and an object oriented one:

$json = JSON->new->allow_nonref;
$perl_scalar = $json->decode( $json_text );

for those that need that extra control.

Monday, October 03, 2011

open expects filename as binary data encoded in the system characterset

I guess this is not a surprise to anyone who thought about how this is supposed to work, but for the sake of being systematic, here is the code:
use strict;
use warnings;
use autodie;
use HTML::Entities;
use Encode;

my $a = HTML::Entities::decode( 'ñ' );

open(my $fh, '>', $a );
print $fh "Without encoding\n";
close $fh;

open(my $fh1, '>', encode( 'UTF-8', $a ) );
print $fh1 "With encoding\n";
close $fh1

And here is the result when run on an system with UTF8 locales:
zby@zby:~/myopera/tmp$ ls
? a.pl ñ
zby@zby:~/myopera/tmp$ cat ñ
With encoding

'a.pl' is the name of the script itself, the mark '?' hides the F1 hexadecimal code and that file contains 'Without encoding'.

Friday, September 30, 2011

Courriel::MMS

I think it is time to announce Courriel::MMS - it is an extension for the new email handling library by Dave Rolsky for processing MMS messages forwarded as emails by the mobile operators. This is still just a github link, no CPAN package yet, but it works in our production servers since Wednesday - so I bet on this code :)

It is a bit heuristic - for example many operators send a subject like 'You have received an mms' - which is useless for us, so the library tries to find something else that would act as the subject we need. For dealing with the various mobile operators, that each send a slightly different format of these emails, I used the Factory design pattern together with Module::Pluggable - this is a novel design for me so I wait for comments.

Tuesday, September 20, 2011

URI->path expects binary data

Update: changed new to path - with new it would be reasonable to require that the uri fed to the parser is already an ASCI string containing the already URI encoded url.
Consider this code:
use 5.010;
use Encode 'encode';
use URI;

my $uri = URI->new( 'http://example.com/' );
say $uri->path( encode("UTF-8", "can\x{00B4}t-make-it-work" ) );
say $uri->path( "can\x{00B4}t-make-it-work" );

The output (in perl 5.14.0) is:
http://example.com/can%C2%B4t-make-it-work
http://example.com/can%B4t-make-it-work

If your page is encoded in UTF8 - then the first one is correct: %C2%B4 is the URI encoded UTF8 encoding of Unicode Character 'ACUTE ACCENT' (U+00B4). If your page encoding is Latin1 - then the second one would be correct - but this is only by accident - in that case you should still use encode("iso-8859-1", ...).

There are probably many other string manipulating libs that should document if their input should be binary encoded data or decoded character strings.

Thursday, September 01, 2011

Names are special

At perl.com Tom Christiansen talks about sorting names, among other things. It appears surprisingly difficult to do properly with many special rules for each language. By coincidence at programming.reddit.com just above a link to that article there is Personal names around the world - a link to a w3c article about even more complications with names. At PhilPapers we had to solve *somehow* a few of these - the result is Text::Names. It is still rather limited: "While it tries to accommodate non-Western names, this module definitely works better with Western names, especially English-style names" - but there is already lots of logic embedded there.

Sunday, August 28, 2011

is_utf8 is useless - can we have is_character?

Consider this code:

$data_structure = utf8::is_utf8($json)
? from_json($json)
: decode_json($json);

taken, together with the is_character suggestion, from otherwise very informative post: Quick note on using module JSON. I have seen similar code in many places. The idea is to check if the string you have is character data or a string of bytes and treat it appropriately. Unfortunately is_utf8 does not do that check:

use strict;
use warnings;

use utf8;
use HTML::Entities;
use JSON;

my $a = HTML::Entities::decode( ' ' );
my $json = qq{{ "a": "$a" }};
print 'is_utf8: ' . ( utf8::is_utf8( $json ) ? 'yes' : 'no' ) . "\n";

my $data_structure = utf8::is_utf8( $json )
? from_json( $json )
: decode_json( $json );


This fails (on my machine) with following output:

is_utf8: no
malformed UTF-8 character in JSON string, at character offset 8 (before "\x{8a0}" }") at a.pl line 12.

If that still is a mystery try this:

use strict;
use warnings;

use HTML::Entities;
use Devel::Peek;

Dump( HTML::Entities::decode( ' ' ) );

the output (on my machine) is:

SV = PV(0x24f2090) at 0x24f3de8
REFCNT = 1
FLAGS = (TEMP,POK,pPOK)
PV = 0x2501620 "\240"\0
CUR = 1
LEN = 16

this string is internally encoded as "\240" i.e. "\x{0a}" which is Latin1 encoding of non-breaking space. It does not have the utf8 flag set - so the code above tries to treat it as UTF8 encoded stream of bytes and fails.

I don't know if we can have is_character easily - but the lack of introspection here is surely painful.

Wednesday, August 24, 2011

CPAN, decoupling and Dependency Injection

Consider the code:

sub fetch
{
my ($self, $uri) = @_;
my $ua = LWP::UserAgent->new;
my $resp = $ua->get( $uri );

...
}


Yes - this is taken from a post by chromatic.

Now imagine that this is code from a CPAN module you installed and that some security concerns require you to replace LWP::UserAgent with LWPx::ParanoidAgent there. Bad luck - you'll probably need to subclass it, override that whole fetch method and pray that it will not change too much with every new release of the original module.

This is really why I am drumming this Dependency Injection drum over and over again - code that uses it is more reusable, more universal:

use Moose;
has 'ua', is => 'ro', default => sub { LWP::UserAgent->new };

sub fetch
{
my ($self, $uri) = @_;
my $ua = $self->ua;
my $resp = $ua->get( $uri );

...
}


Now you would not have any problem with providing a LWPx::ParanoidAgent object for the fetch method to use.

By the way, with classical DI you'd move that LWP::UserAgent->new completely out from the class, here it stays as a 'default' that can be overridden from outside if you need. The problem with classical DI is that you need to have a place where to move that initialization code - here it is sidestepped for the 'normal' usage and you need to worry about it only in the cases where you really need to. Java probably does not have this 'default' mechanism.

Thursday, August 18, 2011

Dependency Injeciton - the cooking metaphor

Let's take a typical recipe. It first describes the goal - and then it goes:

Ingredients:

  • 2-1/4 cups sifted cake flour
  • 2 teaspoons baking powder
  • 1/2 teaspoon salt
  • 1/2 pound (2 sticks) sweet butter, room temperature
    ...

Preparation:
Preheat the oven to 350 degrees Fahrenheit. Butter and line two 8 x 3-inch baking pans or one 12 x 3-inch pan with parchment.


It is not:

Preheat the oven to 350 degrees Fahrenheit. Find a cow and milk her, wait until ...

neither it is:

Preheat the oven to 350 degrees Fahrenheit. Take your credit card and go to the grocery around the corner ...


Dependency injection is about writing your programs in a very similar manner - you first declare the collaborators and then go on with using them.

Thursday, August 11, 2011

So what is Dependency Injection again?

The definition I like the most is that DI is simply about separating object creation from business logic. Object creation - wiring the application - is a special type of code, different from the rest and it is useful to keep it separated. This is similar to how we remove hardcoded magic constants from our code into config files, it can be thought as a Object Oriented extension of that practice. We remove magic constants because we need to change them more frequently than the rest of the code. We do DI because we need to change the object wiring much more frequently than we change business logic and in particular we need to change it in the tests - without that unit tests would not be possible. But it is also different - because the object wiring code is much more complex than configuration files.

But this is not all - DI is also about keeping all object collaborators in it's attributes instead of reaching out for global objects (or signletons which are globals in disguise or class attributes). It thus improves object's encapsulation, makes them more self-reliant and testable. Or maybe this part is not DI - but simply writing Object Oriented code?

On the other hand, the separated out object factories are hard to test because they depend on all the objects classes they create and you want to keep them as small and simple as possible. How many such factories you need? If we have something that has a http request object as attribute - then we cannot build it until the http request arrives from the user. If we keep all collaborators in objects attributes - then we cannot build them until we have all information needed to build all these collaborators first. We thus need one factory per scope.

Tuesday, August 02, 2011

Subclassing applications

Subclassing is a great tool for making small changes to a piece of code to fit it to new requirements. It is as easy as copying code - but it still keeps the new constructs synchronized with later changes to the original. There are problems with inheritance hierarchies - but you need to have a 'hierarchy', not just two classes, to get there.


I imagine that it would be perfect for extended configuration of applications - including web applications. Wouldn't it be great if you could run a slightly changed version of you main web app by making it's code available from PERL5LIB and then subclassing it to change the colors used, add some minor new features and remove some pages for and affiliated site? Or if you could install a blog engine from CPAN, and then subclass it to add new and override old features? This could even make distribution of CPANized applications more popular.

This is one of the things I am experimenting with at Nblog (see also the screencast: Experiments with inheritance in WebNano based applications).

Monday, June 27, 2011

Callbacks versus the Template Method pattern

Let's say you have an object oriented html form validation library and, beside all the default checks (like non-empty or is_number etc.), you want the users of your library to add their own checks coded in the native programming language of your library. You have two simple ways to do that - you can let the form object contain a callback to be used for the check or you can use the Template Method pattern and let programmers subclass your form (or maybe individual field) class and implement their own 'check' method. Both solutions have their own pros and cons but I've never seen a comprehensive comparison of them.

What do you think about them? It seems that some programmers groups prefer one solution over the other (it's hard not to notice how callbacks are popular in the Plack related stuff). Callbacks are simpler, you don't need additional classes there, they don't complicate the program structure, but they are also more constrained. Template Methods are more structural. You can make them call other template methods and make that whole thing fine grained - that is harder with callbacks. In FormHandler I wanted to be able to stack the many generic checks together into lists - but such lists are not very reusable, you cannot override parts of it like you could if they were named methods. The point is that this additional class is another indirection layer and as we know that all programming problems are solvable with in this way :)

Saturday, May 28, 2011

The Bitcoin protocol - a highlevel explanation

Bitcoin is a peer to peer financial protocol. There is no central authority that guarantees that the operations are valid, how can this work? How can you trust strangers with your money? Let's say you are selling something for bitcoins - you receive the amount quoted - how can you verify that the transaction was valid? You need to check three things:

  1. That it was indeed the owner of the sender account that created the transaction.
  2. That the acount has the BTCs that are now being sent - i.e. that it previously received them.
  3. That he has not transfered these BTCs already somewhere else (double spending).

The first check is easy - all transactions are signed. For the second you need to know another transaction that transfers the money to the senders account. Of course now you'll need to verify the other transaction as well - and then, in a recursive fashion, all the others leading to the one that generated the bitcoins (more about generating later). The sender could send you this chain of signed transactions - but in fact he does not need to do that because all the transactions are public.

The third check is more tricky - for this you need to always know which transaction was first and which one is second and then possibly reject the second one if it is double spending. This would be easy with a central authority that would timestamp all transactions and log them somehow - but it is very hard to do in a p2p system. In bitcoin there is also a global log of all transactions - it is called block chain (for it's technical representation). The trick is that to add a valid record to that log you need to solve a hard computational problem. You practically have no chances to do that singlehandedly and you need the other nodes in the network to help you. The sender broadcast his will to transfer money to the whole network and then wait until someone from this network solves the problem and correctly saves the transaction to the global log. This is like going to the notary to make sure that all formalities are met. After the transaction is saved to the log it is very hard to undo that - because you'd need to solve this hard problem again - and without a conspiracy between a significant part of the peers this would be impossible.

To be more precise transactions are not logged individually - but rather in batches called blocks. Such a set of transactions is written to the log in one sweep. This is important for efficiency - but not only.

All of this happens in a distributed, asynchronous manner. This means that it is possible that two nodes will write two new blocks to the transaction log in parallel and we'll get two different and valid versions of the log. What would happen then is that when a next block is written down to one version of the log it will take over all of the transactions from the block in the alternative log version, so they are not lost. But it is possible that the alternative logs contain two conflicting transactions (double spending) - then only one of them will be eventually saved. This showcases one important thing - having the transaction written to the log does not yet guarantee that it will stay there, because it can happen that there exists an alternative, valid log version and that eventually this other one will be the one that is continued by the system. But if you wait until another block is written to the log after the one that you are checking - then you are much more safe. This is the most complex part of the protocol - but the general rule is that the more blocks are written to the log after your - the more safe you are, and the safety grows exponentially.

Now - why so many nodes in the network would spend their time trying to save a new transaction block to the log? This is because they are paid if they succeed. In each new block saved to the log there can be one transaction that generates a specific amount of BTCs (now it is 50 - but it will be less in the future). This is they way new bitcoins are generated.

Another question is how the bitcoin project can maintain that the transactions are anonymous when they are all public? The answer is that what is public is the addresses of the sender and the receiver but not who owns these addresses. It is easy to create new addresses. You can use a new one for every incoming transaction and you can also make transfers between your own accounts to hide the tracks. Maybe it is not total privacy - but it is still better then with current money transfers where the banks know everything.

This introduction leaves out lots of technical details - but I hope that it explains the protocol enough to convince readers that it can work :) For more details have a look at the original bitcoin paper and the bitcoin wiki (just remember that what I call transaction log here is called block chain there).

By the way - I've heard bitcoin makes internet tipping in fashion again - so 113uhu2LrJp8gXGDrDLLDqmFGxnC2e3suB is one of my addresses. The interesting twist to that is that the donations are public - you can view the current ballance at blockexplorer. I've already got some tips - thanks :) Consider this an experiment in micropayments for blog financing.

Update: A critical analysis of the decentralization of the bitcoin protocol: http://www.links.org/?p=1164

Sunday, May 15, 2011

Synthetic attributes

chromatic writes about synthetic attributes. I wonder why this is not more widely used - it's such a simple technique. I've been using it since I discovered Moose and all the time in the back of my head I had this thought: Why people don't use this more widely? It is so obvious solution to the testing problems. Maybe they know something that I don't? But maybe it is just the matter of some guru (like chromatic :) writing about this technique?

PS. Sorry I'll not explain what synthetic attributes mean - this post is only a comment. I cannot currently comment at chromatic's blog.

Tuesday, April 12, 2011

git push and other copy commands

The usual pattern of a copy command:

copy source destination

The pattern of git push command

push destination source:destination

the first destination is the destination repository - the second is the branch (and 'source' is the source branch). I must have skimmed the linked manual dozens of times over many years. There was something that just did not make sense and I imagined that I would have to read some book or something to eventually understand the magic 'ref specs'. It never dawned on me that it was that simple.

The additional difficulty is that the destination repository is usually shortened to 'origin' (because it was the origin for the clone command).

Saturday, March 26, 2011

Drupal like architecture

The Drupal subject reappears in the Perl blogsphere regularly. In my opinion there are three key architectural choices for 'portable plugin apps'. First, obviously, the plugins needs to be highly independent. Second they need to be controlled by pages - that is the page decide what plugins to use. To meet the independence requirement, in the Plack world, the obvious choice for the plugis is that they are simply PSGI apps that in body return a page fragment. This will make it easy to plugin existing wikis and blogs - you just need to remove the header and footer templates and voila you have a plugin instead of a standalone app. You can also use all the Plack infrastructure, for example the Plack::Client if you ever care about scaling your application.

There is one thing that I forgot in the first version of this post - Javascript and CSS. Applications are rarely pure HTML these days - we'll need also some way to gather all the js and css files that the plugins use and link them in the main page. At the main page side this is nothing special - it is not unusual that applications concatenate many Javascript libraries into one file automatically - so this is already well explored. The complication arises from the requirement to pass something more structured then just a HTML fragment in the Plack response from the plugins.

More interesting is the other key choice - how the plugins are supposed to be plugged in. That is how page handlers will choose what plugin to use and what data pass there. As much as I hate the 'program in XML' approach to language syntax - the obvious established standard here is ESI. Maybe we could even steal the semantics and replace the syntax with something saner? Plack based ESI implementation was submitted as an example GSOC idea - I really hope some student will pick it up.

Update: Added js/css handling consideration (thanks for cezio comment below).

Saturday, March 19, 2011

App initialization and web frameworks

Building the application object and its components has nothing to do with serving web pages. The database model setup is exactly the same if you do it for a web application or for your cron utilities and it should also remain the same if you one day decide to make a desktop version of your app. There is no reason that this initialization is a part of web frameworks other then we don't currently have a good standalone application builders. Now every web framework reinvents the wheel and writes one from scratch. Fortunately (in the Perl universe) there are now multiple efforts to create the ultimate configuration engine. There is just one step from a config reader to an application configurator.

As I have already commented elsewhere, I think the ideal for big projects would be a simple config file using simplified syntax that could be changed by the admins plus a Dependency Injection container that would build all the application components from the primitive values provided by this config. This DI container would be a second level configuration - still simple code but touchable only by programmers. For small applications I was quite happy with MooseX::SimpleConfig and Moose type coercions.

Tuesday, March 15, 2011

Reblessing objects

Yesterday I've read the example from Refactoring transcripted into Perl. Nice work (I am not sure about the legal status of this - but I am sure that it is a great advert for the original book). The last refactoring there starts with:

We have several types of movie that have different ways of answering the same question. This sounds like a job for subclasses. We can have three subclasses of movie, each of which can have its own version of charge (Figure 1.14).

This allows me to replace the switch statement by using polymorphism. Sadly it has one slight flaw - it doesn't work. A movie can change its classification during its lifetime. An object cannot change its class during its lifetime.


It then goes on to show how the State Pattern can solve the problem thus stated. I am not so sure about this argumentation - typically the movie data would be stored in a database and the object would be created just for the one transaction - I think it is reasonable to assume that the movie does not change it's classification during the transaction. But OK - all this is just to show how the State Pattern solves the problem even if in this case the problem itself would not be real - for sure there are cases where it would.

Then it got me thinking - well in Perl you can change the class of an object during it's lifetime. I've even seen it done, I don't quite remember where. In general it is considered to be nasty - but is it always? In real life it is normal that things change - a caterpillar becomes a butterfly, a child becomes an adult.

Monday, March 14, 2011

Spark::Form

I remember when when James was starting his project - his basic ideas were exactly the same as our HTML::FormHandler design. Unfortunately he learned about FormHandler after he had started coding - no way to talk him to change his plans and join FormHandler. Reinventing the wheel - but what I can decipher from his latest presentation - is quite interesting. Model integration - which is a major source of the complexity he criticized in HFH - is still lacking but the validation method is intriguing. Maybe cross-pollination will be possible?

Tuesday, March 01, 2011

Plack::Middleware::Auth::Form on CPAN

I've got a bit impatient in waiting for feedback and this week I uploaded Plack::Middleware::Auth::Form to CPAN. This does not mean it is entirely finished - but at least it should be easier to install.

Plack::Middleware::Auth::Form has similar functionality as CatalystX::SimpleLogin, but since it is at the Plack level it can be reused by any Plack based framework.