Nov 29, 2008

[Programming] Interface finals

Somewhere in the very beginning of Mediocre I decided to make an interface called "Definitions" which would hold commonly used constants (like EN_PASSANT, W_KING etc.).

The use of an interface for this was something I thought was the "correct" thing to do at the time. However I have learned a lot about Java-programming since then and now I actually understand the real use for interfaces in Java (which in short is a kind of very basic blueprint for a class, which makes sure certain methods etc. exist).

However it seems I got a bit lucky while doing this. The interface is not "intended" to be used like this but it works very well.

The reason for this is that even though a real class with the same function could be created we would have to either use Definitions.W_KING to access the constants or extend the class, creating a subclass, which is not a good idea in the long wrong (a class can only extend one other class).

But since an interface is used it can be implemented instead, eliminating the need for the "Defintions."-part, while still making room for extending other classes if needed (and a class can implement many interfaces).

A problem would of course would be duplicate names (which can be avoided altogether with clever naming, but anyway) since a whole list of variable names gets taken in the Defintions-interface. However if this occurs, all that is needed is to use e.g. Defintions.W_KING again, defining which W_KING is meant.

In short, the definitions-solution I've used for two years now turned out to be a very good way to handle the constants. And I will stick to it.

1 comment:

Piero said...

I think you can use a static import like this:

"import static mediocre.def.Definitions.*;"