Which is the most practical way to add functionality to this piece of code?

Posted by Adam Arold on Programmers See other posts from Programmers or by Adam Arold
Published on 2013-11-12T00:24:25Z Indexed on 2013/11/12 4:15 UTC
Read the original article Hit count: 310

I'm writing an open source library which handles hexagonal grids. It mainly revolves around the HexagonalGrid and the Hexagon class. There is a HexagonalGridBuilder class which builds the grid which contains Hexagon objects. What I'm trying to achieve is to enable the user to add arbitrary data to each Hexagon. The interface looks like this:

public interface Hexagon extends Serializable {

    // ... other methods not important in this context

    <T> void setSatelliteData(T data);

    <T> T getSatelliteData();
} 

So far so good. I'm writing another class however named HexagonalGridCalculator which adds some fancy pieces of computation to the library like calculating the shortest path between two Hexagons or calculating the line of sight around a Hexagon. My problem is that for those I need the user to supply some data for the Hexagon objects like the cost of passing through a Hexagon, or a boolean flag indicating whether the object is transparent/passable or not.

My question is how should I implement this?

My first idea was to write an interface like this:

public interface HexagonData {

    void setTransparent(boolean isTransparent);

    void setPassable(boolean isPassable);

    void setPassageCost(int cost);
}

and make the user implement it but then it came to my mind that if I add any other functionality later all code will break for those who are using the old interface.

So my next idea is to add annotations like

@PassageCost, @IsTransparent and @IsPassable

which can be added to fields and when I'm doing the computation I can look for the annotations in the satelliteData supplied by the user. This looks flexible enough if I take into account the possibility of later changes but it uses reflection. I have no benchmark of the costs of using annotations so I'm a bit in the dark here.

I think that in 90-95% of the cases the efficiency is not important since most users wont't use a grid where this is significant but I can imagine someone trying to create a grid with a size of 5.000.000.000 X 5.000.000.000.

So which path should I start walking on? Or are there some better alternatives?

Note: These ideas are not implemented yet so I did not pay too much attention to good names.

© Programmers or respective owner

Related posts about design

Related posts about algorithms