Tuesday, March 31, 2009

Roles and data structures

Let's say you have a tree like data structure, something not exactly so uniform as a tree but with enough uniformity that it makes sense that large part of the code is recursive. My example is something representing an HTML Form for editing a complex data structure (with sub-forms etc.). The main form code is used for inflating external data represetntation (key, value pairs) into internal objects and validating it. But there are two additional 'aspects' of this form processing - this is generating the HTML of the form (with all the error indicators and messages) and saving the form data into the data store (by manipulating DBIx::Class schema for example). So you have a tree-like data structure and three separate functionality areas related to it. How do you structure the code?


You can start with defining the data structure and one of the aspects as the 'primary package' - and then add the other aspects as (Moose) roles. This is how it is started in FormHandler - the primary aspect here is the data processing and validation - then saving the the database is added as a role (so you can use it with different data store libraries DBIx::Class, Class::DBI and in the future all the other), the same with rendering - it is a role added to the form class. This is all nice untill you realize that in this way you add the additional roles only to the main form object - but not to the fields (i.e. nodes in the tree) - so you can walk the fields and do the stuff - but you regress here to mostly procedural code.


What we need is to somehow add this role globally to all the field and form classes used.

2 comments:

Ovid said...

You were asking me about this particular post and I have to confess that without seeing a bit more about the structure of the code or the code itself, I'm unsure what to recommend here. It does sound like a problem amenable to roles, but then, since I'm getting closer and closer to the point of recommending that people abandon inheritance directly, I may be biased :)

zby said...

:) I asked you exactly because you seem to advice roles for everything. I need to think about it a bit more to describe the problem more precisely. Maybe I'll catch you at irc.