I was making a swing application, and realized I had a handful of classes that needed access to the same set of constants. I couldnt bring myself to declare one the primary holder of them and place them all in there and have the others reference it; I thought, hey, I'll just have them all inherit from some common place, but Java doesnt do multiple inheritence, BUT I can put infinity interfaces on things. So the idea came to me to dump them all into an interface (it's true, it just naturally occurred to me without doing any research).
I later learned that this is heresy. "In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern" - as discussed here (along with an alternate solution (which I opted to employ)).
I was just fine with this until I was looking at the source code for JDialog
and JFrame
, which read thusly:
public class JDialog extends Dialog implements WindowConstants,
Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
...
and
public class JFrame extends Frame implements WindowConstants,
Accessible,
RootPaneContainer,
TransferHandler.HasGetTransferHandler
{
...
Maybe it's just me, but I sure see a constant interface in there. Even more interesting was one of the author declarations in JDialog, i.e. James Gosling. The father of the language allowed this alleged mistake on his watch?
(Another notable example - SwingConstans)
If the constant interface antipattern is such a bad idea, then why is it so heavily employed in one of the most famous packages of the language (i.e. swing)?
The better solution of using static import
was not available before java 5. Up to this point, abusing interfaces to import constants was considered acceptable because there was no better alternative. Once you have decided that JDialog
implements WindowConstants
(and asserted this in the docs), you cannot undo it without breaking backwards compatibility. Example:
JDialog d = new JDialog();
int flag = d.DISPOSE_ON_CLOSE;
While probably not good style, this is not so unusual and would break if we would change JDialog to use static imports instead of implementing WindowConstants
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With