I was thinking that it might simplify some of my larger apps if I had a way to centralize some of the message strings in one place, the idea being that it's perhaps easier to manage the text in a single location rather than have to look at literals scattered across code in a bunch of different modules.
My first thought was to do this using plain old hashes, along these lines:
open MYFILE, $myfile or die $error_messages{file_open_failed};
But this has a couple of big shortcomings, one of them being that you can't easily do any interpolation on the spot. I decided that what I really wanted was to generate error messages on demand using anonymous subroutines, so I built a simple class that would let me create an object along these lines:
my $error_messages = new MessageLibrary({ file_open_failed => sub {"couldn't open file $_[0]: $!"} }); ... open MYFILE, $myfile or die $error_messages->generate_message('file_op +en_failed', $myfile);
This does the job, but I found the calling syntax a bit inelegant. I decided that I would really like to be able to write things this way:
open MYFILE, $myfile or die $error_messages->file_open_failed($myfile);
That just seems more intuitively readable to me. This turned out to be pretty easy to implement by using an AUTOLOAD method to grab the method name and use it as a key to look up the right subroutine in the hash that was passed to the constructor.
But here's where I come up against the philosophical question. I can easily imagine having a few different MessageLibrary objects in my app: one for error messages, one for debug messages, one for progress/status messages. Yet each of them would have different "methods", even though they're all objects of the same class. So my question to all interested monks is, does this seem like a ridiculous perversion of object-oriented principles? I admit that I'm basically using the arrow-notation-method-call syntax as a convenient form of syntactic sugar (I'm a big believer in writing *readable* code)... so I thought it would be wise to get some outside opinions from informed Monks before I forged ahead with this approach.
BTW, the obvious performance impact of this implementation is not a concern.
In reply to is this a perversion of OO principles? by seattlejohn
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |