API wrapper best practices?
David Cantrell
david at cantrell.org.uk
Mon Mar 25 15:23:42 GMT 2013
On Sat, Mar 23, 2013 at 04:01:43PM +0000, Dave Hodgkinson wrote:
> So I'm writing an interface to an API. It's a simple info request one.
> What top tips do we have for writing one that doesn't suck? I'd
> just go for a new that takes the auth info, methods to go fetch
> the information and being lazy, just let the data be accessible
> through the selfish hash.
>
> I'm not going to create objects for all the data objects at this point
> nor accessors for the individual fields. Well, maybe a few key ones.
I don't like the way that some API modules have eleventy bajillion
objects which get in the damned way of the data. OTOH when I do want
objects, I *really* want them.
> Suggestions for anything better, lazier, more modern?
If you're clever you can auto-generate your objects on the fly. Don't
forget, an object is nothing more than a blessed scalar. It doesn't
really need a module.
All you need to do is to bless things into a namespace and arrange for
that namespace to inherit some methods:
my $object = bless($hash, 'Foo::Bar::Baz');
@Foo::Bar::Baz::ISA = ('Foo::Base');
That can give you the best of both worlds, with minimal coding - you
just need to write the base class - and if you later find that some of
your classes need to be a bit more full-fat, it's easy to implement
them while still using classes generated on the fly for everything else.
--
David Cantrell | Official London Perl Mongers Bad Influence
All principles of gravity are negated by fear
-- Cartoon Law V
More information about the london.pm
mailing list