tags:

views:

51

answers:

2

Hi,

Imagine a strategy whereby you might want parsers for several formats of config file, say INI, XML and YAML for example. Parsing these will result in an instance of a common class say 'Config_Data'.

My thoughts are that as the parser has a very simple mandate, and no state that I can see, it is best implemented as a static class, so you could employ the following:

Parser_Ini::parse(...);
Parser_Xml::parse(...);
...

This doesn't feel entirely correct to me as of course these static classes can't implement an interface etc, but they would seem to make good sense.

I would be interested to know your thoughts on the matter :).

Thanks, James

A: 

You're not necesarily gaining any advantages with this approach, especially if the rest of your code is object oriented. It also prohibits you from using things like the factory pattern to build your parser.

Pace
A: 

Creating static classes have a lot of drawbacks, and I don't see what you gain from it, other than a feeling of convenience, which I find is misleading you.

If you do the classes as regular instance classes, and implement an interface, you will have the freedom of changing implementation on the fly.

The classes that depend on your parser can just take an implementation of your interface as a parameter, and you can thereby inject whatever parser-type you need on that class.

Luhmann
Mm, however with a config parser, isn't it a kinda chicken and egg scenario? Eg in order to select a parser at run time you'd need some config ... which would need to be parsed in the first place. And if you were to instantiate it for the purpose of injecting it into a class, surely only the class knows the type of the config it wants to parse regardless and so it may as well use the static class directly?
jstephenson
Obviously your config parser can't be configured by your config, but that doesn't mean that you can't benefit from a loose coupled architecture. If you need a new parser, you can introduce that without changing any other code, you just need to create the new parser A's sn implementation of your interface and set the new one up wherever you bootstrap your app. And it makes it testable.
Luhmann