If one expects the file format to change over time to accommodate new research data or evolving use cases, using class methods or a singleton object would be a good idea. OOP architecture makes it much easier to support multiple file formats in parallel.
Without objects, you have three options for supporting two file formats:
- Define a second set of parsing functions with ugly names like parse_blah2. Then go all over your existing code inserting if...else statements to select the right set of functions.
- Define the functions for format II in a new package. Now go back to the consumer code and replace all of your calls to parse_XXX(...) with eval("${sParserPackage}::parse_XXX").
- Define a second set of parsing functions and create a dispatch table. Now go all over your code and replace the direct calls to parsing functions with calls to dispatch table members. You've gotten rid of the bulky if...else and eval(...) statements, but you are still making massive code changes. You've also lost some debugging ease since dispatch table methods are going to show up in standard debugging tools as anonymous code references rather than named functions. You simply aren't going to get error messages like Can't locate object method "parse_blah" via package "MyModules::Parse2" Instead you'll get an obscure message about Use of uninitialized value in subroutine entry
Or you could define your parsing process in an object. The only change that would need to be made in your program would be a small bit of code to check the version number and retrieve the correct parser. Any other code using the parser methods would stay the same since it only cares that statements like $oFoo->parse_blah and $sParserClass->parse_blah() behave in a predictable fashion.
Classes and objects, even singleton objects, give one the ability to override and redefine methods without changing a byte of consumer code.
Best, beth
Explanatory note: in Perl, a class method is just a package subroutine whose first parameter is a class name. Calling Foo->fribilate(...) tells Perl to pass "Foo" as the first parameter and to allow overloading. It also lets one use a variable for the package name. ${somevar}::fribilate(...) generates complaints about bare words where operators were expected. That is why we had to use eval(...) in non-object option 2.
|