I have seen interfaces (you know, those abstract class-like things whose names always begin with an I) used for all sorts of strange stuff and I would like to share some of the things I gained from that experience.
Basically, an interface is a great way to ensure that every class that implements it will have certain properties like a collection of public methods. When declaring an interface, no functionality is actually created. Classes that implement an interface have to figure out how to actually make it work -- implement it -- on their own.
Some interfaces are more useful than others. IComparable allows any class to make sure it can be compared with the normal comparison operators. ISerializable, on the other hand, is used more like a flag/annotation. No methods actually have to be defined; the serializer just checks to see if you want this class serialized. It's really pointless to cause a future programmer worry over a possible change to the interface that might blow everything up instead of just registering a simple annotation.
Before making an interface, think about whether an abstract class -- or even just a normal class -- could do the job. (Also, please never make an interface that is intended to be implemented by exactly one class. I'm looking at you, Skype.) A good use of an interface is to allow somebody to extend some subclass of the TileEntity class and also be an IInventory. A bad use is to create an IChunkProvider when you already have an abstract ChunkProvider class. Remember, the purpose of interfaces is to allow inheritance from multiple abstract classes.
There's sometimes some gray area on whether an interface or a common superclass should be used. For example, it might be nice to have IRenderableEntity that defines a draw(Canvas) method. There might be totally separate types of renderables such as ParticleFX and PieceHostile. However, it might be simpler to have both those types extend some abstract GameObject class.
Moral of the story: Try not to go crazy with interfaces. I know it's enterprisey and fun to set up, but requiring excessive implementation will cause pain in the future. Think of the developers you might bring on in the future.
No comments:
Post a Comment