From: Peter Murray-R. <pm...@ca...> - 2004-01-07 18:23:09
|
At 15:08 07/01/2004 +0100, Miguel Howard wrote: > > I guess they all should be 'final'... >I agree > > >> 2- As this class only contains constant definitions (referring to its > >> name), why is it declared as a > >> "class" and not as an "interface" ? There must be a good reason for > >> that, but I don't see which one. > > > > Why should it be an interface? > > Personally, I prefer to have code like CDKConstants.X instead of > > 'implements CDKConstants' in the class definition... > <snip/> >For those who are not familiar with this, one of the 'idioms' of java >programmming is declaring your constants in an interface. This allows all >classes to 'implement' the interface. That way you don't have to prefix >all the uses of constants with the class name. > >It makes no difference in runtime behavior or performance ... it just >eliminates some typing. > >As in: > >interface MyConstants { > final static int CONSTANT_A = 1234; > final static int CONSTANT_B = 2468; >} > >class Foo implements MyConstants { > int bar = CONSTANT_A; > >... If you have already decided to use an interface-based approach then it is natural to put the constants in the interface and not the implementation. A good example of this strategy is the XML-DOM classes (Java 1.4) where every class implements a corresponding interface (Element <... ElementImpl, etc.) Class-specific constants (e.g. symbolic strings) are then defined in the interface I have followed that pattern in developing CML DOM classes. I am not sure whether it's a good idea or not. The merits of interfaces seem to be most important when there is the possibility that more than one implementation may be developed and the user can choose between parsers, DOMs, serializers, etc without rewriting their code. (The different implementations are usually selected by classnames fed to Factory classes). I have also adopted this approach for my own molecular editing software where I define an interface which can be implemented by different libraries. At present much of this is done by CDK lib :-) P. Peter Murray-Rust Unilever Centre for Molecular Informatics Chemistry Department, Cambridge University Lensfield Road, CAMBRIDGE, CB2 1EW, UK Tel: +44-1223-763069 |