The AOP people have this vague notion of "crosscutting concerns," which are things that are not easily modularizeable, because they touch many disperate parts of your program.
The canonical example is logging. Say you want to trace your program's execution. You might begin every sub with something like:
sub foo { log_msg("In subroutine foo") if $DEBUG }
That's a lot of extra typing and redundant code to look at. Good programmers fall violently ill when exposed to redundant code, so the AOP people came up with lots of fancy buzzwords and neato Java stuff to over-engineer a solution: AspectJ. (There's also a very good Perl version.)
But I'm a Perl guy and I don't like all this ivory-tower Javesque bloatism, so I decided to check out what the deal is with these fancy new subroutine attributes. Here's what I came up with.
package Foo; use strict; use warnings; use Attribute::Handlers; sub _log : ATTR(CODE) { my ($package, $symbol) = @_; { no strict 'refs'; no warnings 'redefine'; my $name = *{ $symbol }{NAME}; my $code = \&{ $package . '::' . $name }; *{ $package . '::' . $name } = sub { my $self = shift; print "Entering sub $name\n"; $code->( $self, @_ ); }; } } sub foo : _log { my $self = shift; print "in foo\n"; } 1;
So now I can run perl -MFoo -e 'Foo->foo' and I get:
Entering sub foo in foo
That's just a simple proof-of-concept. Logging isn't really something that's so complicated that it can't be handled in simpler ways. But I think I am going to use this model to associate authorization calls with CGI::Application runmode methods in an app I'm currently working on. Then I can write:
sub rm_secret_stuff : _authz(admin) { ... }
Which would wrap the sub and call $self->authz('admin')->authorize to check if you have permission for that runmode.
Good idea? Bad idea? Other suggestions are always welcome.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Subroutine attributes for solving crosscutting problems
by chromatic (Archbishop) on Sep 08, 2006 at 00:49 UTC | |
by friedo (Prior) on Sep 08, 2006 at 00:52 UTC | |
|
Re: Subroutine attributes for solving crosscutting problems
by Jenda (Abbot) on Sep 08, 2006 at 08:30 UTC | |
|
Re: Subroutine attributes for solving crosscutting problems
by bennymack (Pilgrim) on Sep 08, 2006 at 00:58 UTC | |
|
Re: Subroutine attributes for solving crosscutting problems
by radiantmatrix (Parson) on Sep 11, 2006 at 14:29 UTC | |
|
Re: Subroutine attributes for solving crosscutting problems
by diotalevi (Canon) on Sep 08, 2006 at 18:00 UTC |